分裂多维数组

时间:2011-06-11 00:34:46

标签: php multidimensional-array

我有一个看起来像

的多维数组
$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');

有可能????我该怎么做?

3 个答案:

答案 0 :(得分:2)

最好的办法可能是创建另一个多维数组,将城市作为第一级的键,而不是单独的变量:

$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'];
    }
}

答案 1 :(得分:0)

使用variable variables

的for循环
foreach( $a as $row )
   ${strtolower($row['city']).'_array'}[] = $row;

这实际上将采用每行的'city'元素中的任何内容,将其强制转换为小写,追加_array,并将其用作变量名称并将行追加到其中。

在您的示例中,它将完全按照您的要求执行。

生成这样的变量名称是否安全?除非你完全控制“城市”领域的内容,否则可能不会。

答案 2 :(得分:0)

你可以尝试从这个例子中获得灵感,它展示了如何分成2个数组

$result1=array();
$result2=array();
foreach ($query as $dim) {
  foreach ($dim as $key => $value)
      $result1[] = $key;
      $result2[] = $value;
}