note 67028 added to function.array
| From: | jupiter at nospam dot com | Date: | Fri, 02 Jun 2006 10:33:36 +0000 |
| Subject: | note 67028 added to function.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-112936@lists.php.net to get a copy of this message | ||
<?php
// changes any combination of multiarray elements and subarrays
// into a consistent 2nd level multiarray, tries to preserves keys
function changeMultiarrayStructure($multiarray, $asc = 1) {
if ($asc == 1) { // use first subarrays for new keys of arrays
$multiarraykeys = array_reverse($multiarray, true);
} else { // use the last array keys
$multiarraykeys = $multiarray; // use last subarray keys
} // end array reordering
$newarraykeys = array(); // establish array
foreach ($multiarraykeys as $arrayvalue) { // build new array keys
if (is_array($arrayvalue)) { // is subarray an array
$newarraykeys = array_keys($arrayvalue) + $newarraykeys;
} // if count(prevsubarray)>count(currentarray), extras survive
} // end key building loop
foreach ($multiarray as $newsubarraykey => $arrayvalue) {
if (is_array($arrayvalue)) { // multiarray element is an array
$i = 0; // start counter for subarray key
foreach ($arrayvalue as $subarrayvalue) { // access subarray
$newmultiarray[$newarraykeys[$i]][$newsubarraykey] = $subarrayvalue;
$i++; // increase counter
} // end subarray loop
} else { // multiarray element is a value
foreach ($newarraykeys as $newarraykey) { // new subarray keys
$newmultiarray[$newarraykey][$newsubarraykey] = $arrayvalue;
} // end loop for array variables
} // end conditional
} // end new multiarray building loop
return $newmultiarray;
}
// will change
$old =
array('a'=>1,'b'=>array('e'=>2,'f'=>3),'c'=>array('g'=>4),'d'=>5);
// to
$new =
array('e'=>array('a'=>1,'b'=>2,'c'=>4,'d'=>5),
'f'=>array('a'=>1,'b'=>3,'d'=>5));
// note: if $asc parameter isn't default, last subarray keys used
?>
The new key/value assignment pattern is clearer with bigger arrays.
I use this to manipulate input/output data from my db. Enjoy.
----
Server IP: 66.163.161.117
Probable Submitter: 68.104.56.193
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/function.array.php
Edit -- http://master.php.net/note/edit/67028
Del: integrated -- http://master.php.net/note/delete/67028/integrated
Del: useless -- http://master.php.net/note/delete/67028/useless
Del: bad code -- http://master.php.net/note/delete/67028/bad+code
Del: spam -- http://master.php.net/note/delete/67028/spam
Del: non-english -- http://master.php.net/note/delete/67028/non-english
Del: in docs -- http://master.php.net/note/delete/67028/in+docs
Del: other reasons-- http://master.php.net/note/delete/67028
Reject -- http://master.php.net/note/reject/67028
Search -- http://master.php.net/manage/user-notes.php