0

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

[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,所以所有的技巧都是通过嵌套数组“骑行”,并根据父节点的 id 添加“parent_id”。我知道如何展平数组,但我需要 parent_id 信息。

4

2 回答 2

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
        )

)
于 2013-02-12T12:55:40.520 回答
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));
于 2013-02-12T13:21:17.020 回答