块数组的值

时间:2013-07-17 08:53:30

标签: php arrays foreach parent

你如何像下面这样的数据块?

array(
[0] => array(
    ['id'] => '1',
    ['parent_id'] => ''
)
[1] => array(
    ['id'] => '2',
    ['parent_id'] => ''
)
[2] => array(
    ['id'] => '3',
    ['parent_id'] => '1'
)
[3] => array(
    ['id'] => '3',
    ['parent_id'] => '1'
)
[4] => array(
    ['id'] => '3',
    ['parent_id'] => '2'
)
)

我想将子元素(使用指定的parent_id)分组以执行单独的foreach。

1 个答案:

答案 0 :(得分:3)

你可以做一个简单的foreach并重新排列数组。

$result = array();
foreach ($arr as $element) {
  $result[$element['parent_id']][] = $element;
}

http://phpfiddle.org/main/code/3ar-ixg