Solved

PHP - help with inserting data into the array

Posted on 2012-03-23
8
384 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
  • 4
  • 3
8 Comments
 
LVL 108

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 108

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
 
LVL 108

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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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 108

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

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 upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

920 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now