PHP:修改数组

时间:2009-10-09 06:25:30

标签: php arrays multidimensional-array

需要一些帮助来获取这个分层数组...

    Array (
       [root] => Array ([attr] => Array ([id] => 1) [label] => Array ([value] => My Root)
          [node] => Array (
             [0] => Array ([attr] => Array([id] => 2) [label] => Array([value] => Category 1)
                [node] => Array(
                   [0] => Array ([attr] => Array ([id] => 14) [label] => Array ([value] => Sub-Category 1))
                   [1] => Array([attr] => Array ([id] => 15) [label] => Array([value] => Sub-Category2))
etc, etc,

...并修改它以匹配此数组格式

Array (
   [Category 1] => Array(
      [14] => Sub-Category 1
      [15] => Sub-Category 2
   )
)

2 个答案:

答案 0 :(得分:2)

$newArray = array();
foreach ($array['root']['node'] as $node)
{
  $newArray[ $node['value'] ] = array();

  foreach ($node['node'] as $nestedNode)
    $newArray[ $node['value'] ][ $nestedNode['attr']['id'] ] = $nestedNode['label']['value'];
}

$ newArray - 是你的结果!

答案 1 :(得分:0)

您可以使用Foreach查看每个节点数组。

您应该创建一个递归函数,返回最终数组并查看最近的级别节点。