嵌套数组与parent_id创建平坦

时间:2013-02-12 12:33:38

标签: php arrays nested parent parentid

我想从嵌套数组创建平面数组,如下所示:

[0]=>Array(
  "id"=>1,
  "positions">Array(
    [0]=>Array(
      "id"=>2
      ),
    [1]=>Array(
      "id"=>3
      "positions"=>Array(
         [0]=>Array(
         "id"=>4
         )
      )
   )

这样的事情:

[0]=>Array(
  "id"=>1,
  "parent_id"=>0
  ),
[1]=>Array(
  "id"=>2,
  "parent_id"=>1
  ),
[2]=>Array(
  "id"=>3,
  "parent_id"=>1
  ),
[3]=>Array(
  "id"=>4,
  "parent_id"=>3
  )

我没有嵌套结构中的parent_id,所以所有技巧都是通过嵌套数组“骑”,并添加'parent_id',基于来自父节点的id。我知道如何平坦数组,但我需要parent_id信息。

2 个答案:

答案 0 :(得分:3)

尝试下面的代码:我希望它有用......

<?php

$array = array(array(
  "id"=>1,
  "positions" => 
    array(
       array(
         "id"=>2
       ),
       array(
          "id"=>3,
          "positions"=>
               array(
                  array(
                    "id"=>4
                  )
                )
        )
    )
  ));

echo "<pre>";
print_r(getArray($array));
echo "</pre>";
exit;


function getArray($array,$parent_id = 0)
{
    $result = array();
    foreach ($array as $value)
    {
        $tmp = array();
        $tmp['id'] = $value['id'];
        $tmp['parent_id'] = $parent_id;         
        $result[] = $tmp;
        if(!empty($value['positions']))
        {
            $result= array_merge($result,getArray($value['positions'],$value['id']));
        }

    }

    return $result;


}

?>

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [parent_id] => 0
        )

    [1] => Array
        (
            [id] => 2
            [parent_id] => 1
        )

    [2] => Array
        (
            [id] => 3
            [parent_id] => 1
        )

    [3] => Array
        (
            [id] => 4
            [parent_id] => 3
        )

)

答案 1 :(得分:1)

使用此代码

$result =   array();
function generateArray($array,$parent=0){
    foreach ($array as $key=>$val){
        $tmp = array();
        if(!empty($val['id'])){
            $tmp['id'] = $val['id'];
            $tmp['parent_id'] = $parent;
            $result[] = $tmp;
        }
        if(!empty($val['positions'])){
            $result=array_merge($result,generateArray($val['positions'],$val['id']));
        }
    }
    return $result;
}

您的数组必须具有此结构

$data   =   array(0=>array("id"=>1,"positions"=>array(0=>array("id"=>2),1=>array("id"=>3,"positions"=>array(0=>array("id"=>4))))));

然后调用函数generateArray()

var_dump(generateArray($data));