PHP中一维数组和相关键的未知深度的多维数组

时间:2014-05-08 20:02:47

标签: php arrays recursion

我有一个递归函数,可以抽出看起来像这样的数据

Array
(
[17] => Array
    (
        [cat_id] => 17
        [cat_name] => test.example.1
        [cat_parent] => 16
        [cat_slug] => Test Example 1
    )

[18] => Array
    (
        [16] => Array
            (
                [cat_id] => 16
                [cat_name] => test.example.2
                [cat_parent] => 15
                [cat_slug] => Test Example 2
            )

        [17] => Array
            (
                [15] => Array
                    (
                        [cat_id] => 15
                        [cat_name] => test.example.3
                        [cat_parent] => 6
                        [cat_slug] => Test Example 3
                    )

                [16] => Array
                    (
                        [6] => Array
                            (
                                [cat_id] => 6
                                [cat_name] => test.example.4
                                [cat_parent] => 2
                                [cat_slug] => Test Example 4
                            )

                        [7] => Array
                            (
                                [2] => Array
                                    (
                                        [cat_id] => 2
                                        [cat_name] => test.example.5
                                        [cat_parent] => 0
                                        [cat_slug] => Test Example 5
                                    )

                            )

                    )

            )

    )

)

我找不到一种方法来创建一维的数组,所以我希望有人可以通过一些数组播放来保持一维,保留相关的键。

例如

 Array
 (
   [17] => Array
   (
    [cat_id] => 17
    [cat_name] => test.example.1
    [cat_parent] => 16
    [cat_slug] => Test Example 1
 )

    [16] => Array
 (
    [cat_id] => 16
    [cat_name] => test.example.2
    [cat_parent] => 15
    [cat_slug] => Test Example 2
  )


    [15] => Array
  (
    [cat_id] => 15
    [cat_name] => test.example.3
    [cat_parent] => 6
    [cat_slug] => Test Example 3
   )


    [6] => Array
   (
    [cat_id] => 6
    [cat_name] => test.example.4
    [cat_parent] => 2
    [cat_slug] => Test Example 4
   )


    [2] => Array
   (
    [cat_id] => 2
    [cat_name] => test.example.5
    [cat_parent] => 0
    [cat_slug] => Test Example 5
   )

  )

1 个答案:

答案 0 :(得分:3)

function flatten($array, &$newArray) {
    foreach($array as $i => $el) {
        if (!is_array($array)) {
            return;
        }
        if (isset($el['cat_id'])) {
            $newArray[$i] = $el;
        } elseif (is_array($el)) {
            flatten($el, $newArray);
        }
    }
}
$result = array();
flatten($array, $result);