note 36633 added to function.array

From: Date: Thu, 16 Oct 2003 19:27:02 +0000
Subject: note 36633 added to function.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-58716@lists.php.net to get a copy of this message
Chek this out!!!. Suppose that you want to create an array like the following: <?php $arr1 = ( 0 => array ("customer"=>"Client 1","Item a"), 1 => array ("customer"=>"Client 2","Item b") ); ?> Seems prety easy, but what if you want to generate it dinamically woops!!!. Imagine that you have a file with thousands of lines and each line is a purchase order from diferent clients: <?php /*function to add elements*/ function addArray(&$array, $id, $var) { $tempArray = array( $var => $id); $array = array_merge ($array, $tempArray); } /*The same as above but the element is an array*/ function addArrayArr(&$array, $var, &$array1) { $tempArray = array($var => $array1); $array = array_merge ($array, $tempArray); } /*labels of our array or heders of the file*/ $keyarr = array("customer","item"); /*info that may you read from a file line 1 and 2*/ $valarr0 = array("Client 1","Item a"); $valarr1 = array("Client 2","Item b"); $numofrows = 2;/*In our case is just two lines*/ $tmpArray = array(); for($i = 0; $i < $numofrows; $i++){ $tmp = "valarr$i"; $tmpvar = ${$tmp};/*Using var of vars tricky tricky*/ foreach( $keyarr as $key=>$value){ addArray($tmparr,$tmpvar[$key],$value); } addArrayArr($finalarr,$i,$tmparr); } /*voila all it's perfectly ordered on finalarr*/ /*Here we just print the info but you can insert it into a database*/ echo "Customer: ".$finalarr[0]["customer"]."<br>"; echo "Item: ".$finalarr[0]["item"]."<br>"; echo "Customer: ".$finalarr[1]["customer"]."<br>"; echo "Item: ".$finalarr[1]["item"]."<br>"; ?> The lines above should print something like: Customer: Client 1 Item: Item a Customer: Client 2 Item: Item b I hope someone find this useful. ---- Manual Page -- http://www.php.net/manual/en/function.array.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+36633 Delete -- http://master.php.net/manage/user-notes.php?action=delete+36633&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+36633&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#58716) next »