用定界符递归展平多向数组键

时间:2018-11-16 19:04:17

标签: php

我正在尝试使用递归php函数使用定界符将多方向键转换为键数组。这是我到目前为止所拥有的。不知道为什么要返回部分数组。

$array = [
        'arr' => 1,
        'arr2' => [
            '_arr2' => 'test',
            '_arr2_2' => 'test 2',
            '_arr2_3' => 3,
            '_arr2_4' => [
                '__arr2' => 'tt',
                '__arr2_2' => 'ttww',
                'sub-sub-field' => [
                    'ww' => 1
                ]
            ],
            '_arr2_5' => [
                '__arr2_5' => 'some'
            ]
        ],
        'arr3' => 'test',
        'arr4' => null,
        'arr5' => [
            '_arr5' => [
                '___arr5' => 1
            ],
            '_arr5_1' => null
        ],
    ];

function print_array_reccur ($array, $str = '') 
{
    if (empty($array)) return null;

    $arr = [];

    foreach ($array as $key => $val) 
    {
        if (is_array($val)) 
        {
            if ($str == '') 
            {
                $arr = print_array_reccur($val, $key);
            } 
            else 
            {
                $arr = print_array_reccur($val, $str . '/' . $key);
            }
        } 
        else 
        {
            if ($str == '') 
            {
                $arr[$key] = $val;
            } 
            else 
            {
                $arr[$str . '/' . $key] = $val;
            }
        }
    }

    return $arr;
}

目前,我正在获取下面的部分数组输出。知道为什么会这样吗?

   Array
(
    [arr5/_arr5/___arr5] => 1
    [arr5/_arr5_1] => 
)

1 个答案:

答案 0 :(得分:0)

据我所知(在测试用例的帮助下-总是有帮助的),问题是当您从子数组处理中返回新值时,这将覆盖现有内容。我已经评论了这两行,但是只是我已经使用+=将新数据添加到现有数组数据中了。

function print_array_reccur ($array, $str = '')
{
    if (empty($array)) return null;

    $arr = [];

    foreach ($array as $key => $val)
    {
        if (is_array($val))
        {
            if ($str == '')
            {
                // Add new data into the existing array using +=
                $arr += print_array_reccur($val, $key);
            }
            else
            {
                // Add new data into the existing array using +=
                $arr += print_array_reccur($val, $str . '/' . $key);
            }
        }
        else
        {
            if ($str == '')
            {
                $arr[$key] = $val;
            }
            else
            {
                $arr[$str . '/' . $key] = $val;
            }
        }
    }

    return $arr;
}

希望返回值是您的后......

Array
(
    [arr] => 1
    [arr2/_arr2] => test
    [arr2/_arr2_2] => test 2
    [arr2/_arr2_3] => 3
    [arr2/_arr2_4/__arr2] => tt
    [arr2/_arr2_4/__arr2_2] => ttww
    [arr2/_arr2_4/sub-sub-field/ww] => 1
    [arr2/_arr2_5/__arr2_5] => some
    [arr3] => test
    [arr4] => 
    [arr5/_arr5/___arr5] => 1
    [arr5/_arr5_1] => 
)