将递归数组转换为2D数组

时间:2019-02-20 12:54:28

标签: php arrays multidimensional-array

我有这样的多维数组格式

<?php 
    $array = array
    (
     "agent_code" => "00920860",
     "recruiter"  => "00000001",
     "children"   => array
       (
        "00910066" => array
          (
           "agent_code" => "00910066",
           "recruiter"  => "00920860",
           "children"   => array
             (
              "00917653" => array
                (
                 "agent_code" => "00917653",
                 "recruiter"  => "00910066"
                )
             )
          )
       )
    );
  ?>

如何将格式结果更改为这样

    Array
    (
    [0] => Array (
                [agent_code] => 00920860
                [recruiter] => 00000001
            )
    [1] => Array (
                [agent_code] => 00923464
                [recruiter] => 00920860
            )
    [2] => Array (
                [agent_code] => 00917653
                [recruiter] => 00910066
            )
    )

1 个答案:

答案 0 :(得分:1)

这是您要查找的摘录,

function recursive($array = [], $result = [], $i)
{
    if (empty($result))
    {
        $result = [];
    }
    foreach ($array as $key => $value)
    {
        //If $value is an array.
        if (is_array($value) && is_array(array_values($value)))
        {
            $result = recursive($value, $result, ++$i);
        }
        else
        {
            $result[$i][$key] = $value;
        }
    }
    return $result;
}

$a = recursive($array, [], 0);
$a = array_values($a);
print_r($a);

输出

Array
(
    [0] => Array
        (
            [agent_code] => 00920860
            [recruiter] => 00000001
        )

    [1] => Array
        (
            [agent_code] => 00910066
            [recruiter] => 00920860
        )

    [2] => Array
        (
            [agent_code] => 00917653
            [recruiter] => 00910066
        )

)

这里是working code