我有一个看起来像的多维数组
$a[] = array('id' => '1', 'city' => 'Delhi', 'pin' => '11A', 'country' => 'India');
$a[] = array('id' => '2', 'city' => 'Delhi', 'pin' => '11B', 'country' => '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');
我需要根据城市名称将它们拆分成单独的数组。例如
$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');
有可能吗????我该怎么做?
最好的方法可能是创建另一个多维数组,将城市作为第一级的关键字,而不是单独的变量:
$result = array();
foreach ($a as $v) {
$city = $v['city'];
if (!isset($result[$city])) $result[$city] = array();
$result[$city][] = $v;
}
所以你会得到:
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
)
...
)
然后你可以访问它像:
foreach ($result as $city => $elements) {
echo $city;
foreach ($elements as $element) {
echo $element['pin'];
}
}
具有可变变量的循环
foreach( $a as $row )
${strtolower($row['city']).'_array'}[] = $row;
实际上,这将采用每行的"city"元素中的任何内容,将其强制转换为小写,附加_array
,并将其用作变量名并将行附加到其中。
在您的示例中,它将完全按照您的要求执行。
生成这样的变量名安全吗?除非你能完全控制"城市"领域的发展,否则可能不会。
您可以尝试从这个例子中汲取灵感,它展示了如何划分为2个数组
$result1=array();
$result2=array();
foreach ($query as $dim) {
foreach ($dim as $key => $value)
$result1[] = $key;
$result2[] = $value;
}