note 102665 modified in function.eval by danbrown
[email protected] Mon, 28 Feb 2011 06:41:55 -0800
| Newsgroups | php.notes |
|---|---|
| Message-ID | <[email protected]> |
This function is to automatically sort a 2 dimensional array (like that from mysql fetches) into unlimited dimension array's
<?php
/*
@param $array mysql fetch array
@param $row_key array of rowkeys to be used ex array('country', 'state', 'city');
*/
function LoopRowKey($array, $row_key, &$result=null){
foreach($array as $key => $value){
$i='';
$row_key = (array)$row_key;
foreach($row_key as $var){
if(isset($value[$var])){
$var = $value[$var];
$i .= "['$var']";
}
}
eval("\$result$i".'[]'." = \$value;");
}
return $result;
}
//this function will turn:
$array = array{
array{
'id' => '1',
'country' => 'canada',
'state' => 'QC',
'city' => 'montreal',
}
array{
'id' => '2',
'country' => 'canada',
'state' => 'ON',
'city' => 'toronto',
}
array{
'id' => '3',
'country' => 'canada',
'state' => 'QC',
'city' => 'quebec',
}
};
$row_key = array('country', 'state');
$result = LoopRowKey($array, $row_key);
//will give
$result = array{
'canada' => array{
'QC' => {
'0' => array{
'id' => '1',
'country' => 'canada',
'state' => 'QC',
'city' => 'montreal',
}
'1' => array{
'id' => '3',
'country' => 'canada',
'state' => 'QC',
'city' => 'quebec',
}
}
}
'ON' => {
'0' => array{
'id' => '2',
'country' => 'canada',
'state' => 'ON',
'city' => 'toronto',
}
}
};
?>
--was--
This function is to automatically sort a 2 dimensional array (like that from mysql fetches) into unlimited dimension array's
/*
@param $array mysql fetch array
@param $row_key array of rowkeys to be used ex array('country', 'state', 'city');
*/
function LoopRowKey($array, $row_key, &$result=null){
foreach($array as $key => $value){
$i='';
$row_key = (array)$row_key;
foreach($row_key as $var){
if(isset($value[$var])){
$var = $value[$var];
$i .= "['$var']";
}
}
eval("\$result$i".'[]'." = \$value;");
}
return $result;
}
//this function will turn:
$array = array{
array{
'id' => '1',
'country' => 'canada',
'state' => 'QC',
'city' => 'montreal',
}
array{
'id' => '2',
'country' => 'canada',
'state' => 'ON',
'city' => 'toronto',
}
array{
'id' => '3',
'country' => 'canada',
'state' => 'QC',
'city' => 'quebec',
}
};
$row_key = array('country', 'state');
$result = LoopRowKey($array, $row_key);
//will give
$result = array{
'canada' => array{
'QC' => {
'0' => array{
'id' => '1',
'country' => 'canada',
'state' => 'QC',
'city' => 'montreal',
}
'1' => array{
'id' => '3',
'country' => 'canada',
'state' => 'QC',
'city' => 'quebec',
}
}
}
'ON' => {
'0' => array{
'id' => '2',
'country' => 'canada',
'state' => 'ON',
'city' => 'toronto',
}
}
};
http://php.net/manual/en/function.eval.php