【问题标题】:How do I reduce this function into a recursive one?如何将此函数简化为递归函数?
【发布时间】:2016-07-10 09:44:44
【问题描述】:

我有一个函数,它从输入数组中返回一个带有空键的数组。问题是我一直在处理不一致的数据。数据可以进入任何级别的嵌套数组。例如,

$inputArray = [
    'a' => 'value a',
    'b' => [
        1 => [],
        2 => 'value b2',
        3 => [
            'x' => 'value x'
            'y' => '' 
        ],
    'c' => ''
    ],
];

我需要一个将这种数据转换为字符串的输出。所以,

$outputArray = [
    'empty' => [
        'b[1]',
        'b[3][y]',
        'c'
    ]
];

到目前为止,这是我获取具有空值的键的方法:

$outputArray = [];
foreach ($inputArray as $key => $value) {
    if (is_array($value)) {
        foreach ($value as $index => $field) {
            if (is_array($field)) {
                foreach ($field as $index1 => $value1) {
                    if (empty($value1)) {
                        array_push($outputArray['empty'], $key . '[' . $index . ']' . '[' . $index1 . ']');
                    }
                }
            }
            if (empty($field)) {
                array_push($outputArray['empty'], $key . '[' . $index . ']');
            }
        }
    }
    if (empty($value)) {
        array_push($outputArray['empty'], $key);
    }
}
return $outputArray;

正如我所说,输入数组可以嵌套到任何级别。每次数组再嵌套一层时,我都无法继续添加 if (is_array) 块。我相信它可以使用递归函数来解决,但我似乎无法弄清楚如何。请帮我解决一下这个。谢谢。

【问题讨论】:

    标签: php arrays recursion multidimensional-array


    【解决方案1】:

    你对递归函数的看法是对的,但你也应该注意递归,无论我们是在递归还是在递归之外。棘手的部分是将当前级别的键传递给递归函数:

    function findEmpties($input, $currentLevel = null) {
        static $empties = [];
    
        foreach ($input as $key => $value) {
            $levelItem = $currentLevel ? "{$currentLevel}[{$key}]" : $key;
            if (empty($value)) {
                $empties['empty'][] = $levelItem;
            } else {
                if (is_array($value)) {
                    findEmpties($value, $levelItem);
                }
            }
        }
    
        return $empties;
    }
    

    Live demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-03
      • 2021-12-17
      • 2021-11-03
      • 2020-08-20
      • 1970-01-01
      相关资源
      最近更新 更多