note 102665 modified in function.eval by danbrown

From: Date: Mon, 28 Feb 2011 14:41:55 +0000
Subject: note 102665 modified in function.eval by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-177404@lists.php.net to get a copy of this message
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

« previous php.notes (#177404) next »