Solved

PHP - help with inserting data into the array

Posted on 2012-03-23
8
403 Views
Last Modified: 2012-06-27
Hi there,

I have foreach loop that produces values:

Date => 03-19-12
Category => Excessive Verbal Abuse
Decision => Innocent

Date => 03-15-12
Category => Avoiding AFK Detection
Decision => Guilty

Open in new window


How do I insert those values like in 3 columns into array and then get the data out from it?
0
Comment
Question by:mropenmind
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 37756596
It would appear that each of those two data sets contains the three named elements, Date, Category, and Decision.  So you might have an associative array (one that uses named keys) to hold these three named elements.  That array, in turn, can be an element in another array.  By using nested iterators you can access all of the information, first in the master array, then in the sub-arrays.
0
 

Author Comment

by:mropenmind
ID: 37756647
foreach($matches[1] as $num=>$value) {

$date = preg_replace("/ .*/","",$matches[3][$num]);
	$newReallyUsefulArray = array();

 foreach ($dateArray as $dt)
    {
        $test_date = date('m-d-y', strtotime($dt));
		$pos = strpos($test_date, $date);
	    if ($pos !== false) 
        {
		
		   $tmp_array_date = $date;
  $tmp_array_category = $matches[5][$num];
  $tmp_array_decision = strip_tags($matches[6][$num]);
  
  
  $tmp_array = array(
   'date' => $tmp_array_date,
   'category' => $tmp_array_category,
   'decision' => $tmp_array_decision
    
  );
  
    array_push($newReallyUsefulArray, $tmp_array);
 
        } 
   }
print_r($newReallyUsefulArray);   
}

Open in new window


It works but for those entries in the table that doesn't match the date, I get:
Array
(
)
Array
(
)
Array
(
)
Array
(
)
0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 400 total points
ID: 37756658
This shows the principles.  Please post back if you have any questions.
http://www.laprbass.com/RAY_temp_mropenmind.php
<?php // RAY_temp_mropenmind.php
error_reporting(E_ALL);
echo "<pre>";

// REQUIRED SINCE PHP 5.1+
date_default_timezone_set('America/New_York');


// TEST DATA FROM THE POST AT EE
$htm = <<<HTM
							<table class="table-gradient">
								<thead>
									<tr>
										<th scope="col"><a href="" style="text-decoration: none; color: #FFF;">NICKNAME</a></th>
										<th scope="col"><a href="gm_decisions.php?sort=count&dir=DESC" style="text-decoration: none; color: #FFF;">GM</a></th>
										<th scope="col"><a href="gm_decisions.php?sort=date_decided&dir=DESC" style="text-decoration: none; color: #FFF;">Date Decided</a></th>
										<th scope="col"><a href="gm_decisions.php?sort=decision_id&dir=DESC" style="text-decoration: none; color: #FFF;">Decision ID</a></th>
										<th scope="col">Category</th>
										<th scope="col">Decision</th>
									</tr>
								</thead>

								<tbody>

																<tr>
									<td><a href="playerview.php?account_id=5640930">lHadesl</a></td>
									<td><a href="gm_decisions.php?searchType=gm&search=Rejanu">Rejanu</a></td>
									<td>03-21-12 17:42</td>
									<td>146152</td>
									<td>Excessive Verbal Abuse</td>
									<td><a href="javascript:void(0);" >Guilty</a></td>
								</tr>

																<tr>
									<td><a href="playerview.php?account_id=3012910">Mezmerise</a></td>
									<td><a href="gm_decisions.php?searchType=gm&search=Rejanu">Rejanu</a></td>
	<!-- CHANGE HERE -->			<td>04-01-12 11:50</td>
									<td>145933</td>
									<td>Excessive Verbal Abuse</td>
									<td><a href="javascript:void(0);" >Innocent</a></td>
								</tr>


								</tbody>
							</table>
HTM;

// MAP OF TABLE DATA TO ARRAY KEYS
$map = array
( 3 => 'Date'
, 5 => 'Category'
, 6 => 'Decision'
)
;

// KEEP THE FINAL OUTPUT HERE
$arr = array();

// SCRAPE THE HTML TO GET TABLE DATA
$bod = strpos($htm, '<tbody>');
$htm = substr($htm, $bod);
$trs = explode('<tr>', $htm);

// EACH TABLE ROW
foreach ($trs as $tr)
{
    // EACH TABLE DATA
    $tds = explode('<td>', $tr);
    foreach ($tds as $key=> $td)
    {
        // CLEAN UP THE UNWANTED HTML TAGS
        $tds[$key] = trim(strip_tags($td));
    }

    // SKIP TABLE ROWS THAT DO NOT HAVE ENOUGH DATA
    if (empty($tds[3])) continue;

    // MAP THE DATA BY ASSOCIATIVE NAME INTO THE OUTPUT ARRAY
    foreach ($map as $key => $nom)
    {
        $out[$nom] = $tds[$key];
    }
    $arr[] = $out;
}

// SHOW THE WORK PRODUCT
print_r($arr);

Open in new window

0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
LVL 110

Expert Comment

by:Ray Paseur
ID: 37756673
Looks like there is some mixing of apples and oranges here.  Technically you can use regular expressions to parse HTML, if the HTML is highly predictable.  This is sort of like saying you can use a wrench to drive nails.  It may not be the best tool for the job, and the assumption that regular expressions must be the starting point (or even should be the starting point) may lead you into a complicated morass of fiddly punctuation and indecipherable data types.

If you are getting exactly what you want and expect from a regular expression, great.  If not, you may find that simpler string manipulation functions get you easier to use (and easier to debug) processes.  Just a thought...
0
 
LVL 14

Assisted Solution

by:Scott Madeira
Scott Madeira earned 100 total points
ID: 37756676
Something like this may work...  May be a syntax error here or there.

<?php

// Your foreach loop - not sure how you get the values but we'll assume
// they have the variable names $date, $category, $decision

$index=0;
foreach ( whatever your loop is){
	
	$data[$index]['date'] = $date;	
	$data[$index]['category'] = $category;	
	$data[$index]['decision'] = $decision;	
	$i++;
}	

// Getting data backout of your array

// Loop through your groups of data
foreach ( $data as $value){
	
	// Loop through each group of three elements
	// assign the value to a variable with the same name as the key value (date, category, etc.)	
	foreach ($value as $key => $datavalue){	
		$$key = $datavalue;		
	}

        //Do something with the data row here	
}	
?>

Open in new window

0
 

Author Comment

by:mropenmind
ID: 37756783
What I needed to do is:

Take : $newReallyUsefulArray = array(); out from the array and put the print_r($newReallyUsefulArray); after foreach loop but not inside it.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 37756784
It works but for those entries in the table that doesn't match the date, I get:
Array
(
)
Array
(
)
Array
(
)
Array
(
)
There are some PHP functions that can help you get away from empty or unset data elements.  See the online man pages here.
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/function.empty.php
http://php.net/manual/en/function.array-key-exists.php

This is required reading for anyone using PHP
http://php.net/manual/en/types.comparisons.php

If you want to get something of a foundation in how to use the language, these are good learning resources.
http://php.net/tut.php

And this little book will not make you a pro, but it is easy to read, provides some structured learning and has great examples.  All that, and it comes with a code library you can download and modify for your own use.  Now in its fourth printing, it has been a permanent part of my professional library since Edition One.
http://www.sitepoint.com/books/phpmysql4/

Best regards, ~Ray
0
 

Author Comment

by:mropenmind
ID: 37756815
It works now, but thanks for help Ray.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
MySqli Real Escape String and SQL Injection 1 49
MySQL Persistent Connections 10 35
Understanding ping command in Ubuntu 5 33
How do I remove "" from json_encode 5 22
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question