【问题标题】:walk through array with nested output in PHP在 PHP 中遍历带有嵌套输出的数组
【发布时间】:2021-06-21 12:57:47
【问题描述】:

我有这个代码:

foreach ($_POST as $key1 => $item1):
    if (is_array($item1)):
        foreach ($item1 as $key2 => $item2):
            if (is_array($item2)):
                foreach ($item2 as $key3 => $item3):
                    if (is_array($item3)):
                        foreach ($item3 as $key4 => $item4):
                            $_POST[$key1][$key2][$key3][$key4] = empty($item4) ? NULL : $item4;
                        endforeach;
                    else:
                        $_POST[$key1][$key2][$key3] = empty($item3) ? NULL : $item3;
                    endif;
                endforeach;
            else:
                $_POST[$key1][$key2] = empty($item2) ? NULL : $item2;
            endif;
        endforeach;
    else:
        $_POST[$key1] = empty($item1) ? NULL : $item1;
    endif;
endforeach;

$_POST 是一个 4 级数组,array_walk() 将返回我的第一级数组(这是我不想要的)。

问题是如何使用重复块简化此代码?

【问题讨论】:

  • 您能否展示您想要实现的目标,将传入什么以及预期的输出是什么(摘要会做)。
  • 请先在此处解释您需要实现什么,而不是仅仅卸载您的代码。

标签: php arrays array-walk


【解决方案1】:

这是一项递归工作,在这里使用array_walk_recursive 最容易实现。

请确保您了解您的代码的作用,empty 对零返回 true,这可能是个问题。

$input = [
    'param1' => [
        'sub1_1' => [
            'sub1_1_1' => [
                'sub1_1_1_1' => 'foo',
                'sub1_1_1_2' => '',
                'sub1_1_1_3' => 0,
                'sub1_1_1_4' => 'bar',
                'sub1_1_1_5' => false,
                'sub1_1_1_6' => [
                    'sub1_1_1_6_1' => 'baz',
                    'sub1_1_1_6_2' => ''
                ]
            ]
        ]
    ]
];

array_walk_recursive($input, function(&$value)
{
    $value = (empty($value)) ? null:$value;
});

// Verify that false-y values were changed to null
assert($input['param1']['sub1_1']['sub1_1_1']['sub1_1_1_2']===null, 'Empty string should be normalized to null');
assert($input['param1']['sub1_1']['sub1_1_1']['sub1_1_1_3']===null, 'Zero should be normalized to null');
assert($input['param1']['sub1_1']['sub1_1_1']['sub1_1_1_5']===null, 'False should be normalized to null');

// Check out the state of the normalized input
var_dump($input);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多