Splitting Multi Dimensional Array
i have an multi-dimensional array which looks like
$a[] = array('id' => '1', 'city' => 'Delhi', 'pin' => '11A', 'country' => 'India');
$a[] = array('id' => '2', 'city' => 'Delhi', 'pin' => '11B', 'c开发者_JS百科ountry' => 'India');
$a[] = array('id' => '3', 'city' => 'Delhi', 'pin' => '11C', 'country' => 'India');
$a[] = array('id' => '5', 'city' => 'Bombay', 'pin' => '22A', 'country' => 'India');
$a[] = array('id' => '6', 'city' => 'Bombay', 'pin' => '22B', 'country' => 'India');
$a[] = array('id' => '8', 'city' => 'Bombay', 'pin' => '22D', 'country' => 'India');
$a[] = array('id' => '9', 'city' => 'Chennai', 'pin' => '44A', 'country' => 'India');
$a[] = array('id' => '10', 'city' => 'Chennai', 'pin' => '44B', 'country' => 'India');
$a[] = array('id' => '12', 'city' => 'Chennai', 'pin' => '44D', 'country' => 'India');
i need to split them into separate array based on city name. eg
$delhi_array[] = array('id' => '1', 'city' => 'Delhi', 'pin' => '11A', 'country' => 'India');
$delhi_array[] = array('id' => '2', 'city' => 'Delhi', 'pin' => '11B', 'country' => 'India');
$bombay_array[] = array('id' => '5', 'city' => 'Bombay', 'pin' => '22A', 'country' => 'India');
is it possible???? how do i do it?
The best thing to do would probably be to create another multi-dimensional array, with the cities as the keys for the first level, instead of separate variables:
$result = array();
foreach ($a as $v) {
$city = $v['city'];
if (!isset($result[$city])) $result[$city] = array();
$result[$city][] = $v;
}
So you'd get:
Array
(
[Delhi] => Array
(
[0] => Array
(
[id] => 1
[city] => Delhi
[pin] => 11A
[country] => India
)
...
[Bombay] => Array
(
[0] => Array
(
[id] => 5
[city] => Bombay
[pin] => 22A
[country] => India
)
...
[Chennai] => Array
(
[0] => Array
(
[id] => 9
[city] => Chennai
[pin] => 44A
[country] => India
)
...
)
Then you could access it like:
foreach ($result as $city => $elements) {
echo $city;
foreach ($elements as $element) {
echo $element['pin'];
}
}
A for loop with variable variables
foreach( $a as $row )
${strtolower($row['city']).'_array'}[] = $row;
This will actually take whatever is in the 'city' element of each row, cast it to lowercase, append _array
, and use that as the variable name and append the row to it.
In your example, it will do exactly what you asked.
Is it safe to be generating variable names like that? Probably not unless you have total control over what can go in the "city" field.
you could try to inspirate from this exemple, it show how to divise into 2 arrays
$result1=array();
$result2=array();
foreach ($query as $dim) {
foreach ($dim as $key => $value)
$result1[] = $key;
$result2[] = $value;
}
精彩评论