从嵌套关联数组中删除值为空或“”或[]的键值对

问题描述 投票:0回答:2

我有以下数组:

$variables = [
    "id" => "discountCodeID",
    "test" => null,
    "codeDiscount" => [
        "code" => "discountCode",
        "title" => null,
        "startsAt" => "discountStartsAt",
        "endsAt" => "",
        "usageLimit" => "discountUsageLimit",
        "usesPerOrderLimit" => "discountUsesPerOrderLimit",
        "customerBuys" => [
            "value" => [],
            "items" => "discountCustomerBuysItems"
        ],
        "customerGets" => [
            "value" => "discountCustomerGetsValue",
            "items" => "discountCustomerGetsItems"
        ],
        "customerSelection" => "",
        "appliesOncePerCustomer" => "discountAppliesOncePerCustomer"
    ]
];

现在我想删除所有值为

null
""
[]
的键值对。 但问题是由于嵌套数组,使用简单的数组过滤器不起作用。所以我采取了以下方法:

foreach ($variables as $key => $value) {
    if (is_null($value) || $value === '' || (is_array($value) && empty($value))) {
        unset($variables[$key]);
    } elseif (is_array($value)) {
        $variables[$key] = removeEmptyValuesFromArray($value);
    }
}

function removeEmptyValuesFromArray($array) {
    foreach ($array as $key => $value) {
        if (is_null($value) || $value === '' || (is_array($value) && empty($value))) {
            unset($array[$key]);
        } elseif (is_array($value)) {
            $array[$key] = removeEmptyValuesFromArray($value);
        }
    }
    return $array;
}

print_r($variables);

这段代码可以工作,但问题是,随着嵌套数组级别的增加,数组可能会变得更大。在这种情况下,这当然不是一个好的解决方案。

那么在这种情况下你会采取什么方法呢?

Arigato Gozaimasu!

php arrays optimization multidimensional-array associative-array
2个回答
0
投票

您的函数中已经有递归。

所以你不需要在它外面的第一个

foreach
循环。您可以按如下方式简化代码:

function removeEmptyValuesFromArray($array) {
    foreach ($array as $key => $value) {
        if (empty($value)) {
            unset($array[$key]);
        } elseif (is_array($value)) {
            $array[$key] = removeEmptyValuesFromArray($value);
        }
    }
    return $array;
}

$variables = removeEmptyValuesFromArray($variables);

另请注意,您可以将

is_null($value) || $value === '' || (is_array($value) && empty($value))
替换为
empty($value)


0
投票

为了满足子数组的所有元素都被删除的边缘情况(因此子数组本身也应该被删除),我建议对递归函数中的测试稍微重新排序:

function removeEmptyValuesFromArray($array) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $value = removeEmptyValuesFromArray($value);
            $array[$key] = $value;
        }
        if (is_null($value) || $value === '' || (is_array($value) && empty($value))) {
            unset($array[$key]);
        }
    }
    return $array;
}
© www.soinside.com 2019 - 2024. All rights reserved.