【问题标题】:Unset array key if value is empty如果值为空,则取消设置数组键
【发布时间】:2018-04-11 11:25:18
【问题描述】:
Array
(
    [2] => Array
        (
            [option_id] => 2
            [price] => 15
            [processor] => Array
                (
                    [3] => Array
                        (
                            [processor_id] => 3
                            [price] => 15
                        )

                    [4] => Array
                        (
                            [processor_id] => 4
                            [price] => 15
                        )

                )

        )

    [3] => Array
        (
            [option_id] => 3
            [price] => 15
            [processor] => Array
                (
                    [3] => Array
                        (
                            [processor_id] => 3
                            [price] => 15
                        )

                    [4] => Array
                        (
                            [processor_id] => 4
                            [price] => 15
                        )

                )

        )

    [4] => Array
        (
            [processor] => Array
                (
                    [3] => Array
                        (
                            [price] => // empty value
                        )

                    [4] => Array
                        (
                            [price] => // empty value
                        )

                )

        )

)

我有这个数组,现在我想取消设置该数组没有任何值,就像在最后一个数组中没有给出值一样,所以我想取消设置整个数组键。

在这个数组中,我有空值,所以我如何取消设置 [4] 键。那么没有foreach循环是否可能。

【问题讨论】:

  • 用 foreach 做 unset 或 array_splice
  • 是的。你试过什么了?哪里出了问题?你能描述一下这个问题吗?目前你只是在找人做你的工作。
  • 没有内置函数可以执行此操作,因此您最终将不得不以某种方式(隐藏或可见)使用循环(可能是递归)。你有没有尝试过?
  • 谢谢@JeesKDenny 我得到了你的想法的解决方案。现在它工作正常。

标签: php arrays


【解决方案1】:

您可以为此使用array_filter。由于您没有提供任何代码,我建议您阅读 php.net 上的文档。

function filter_function($var) {
    // return an expression evaluating to true to keep value
    return ($var["option_id"]);
}

$filtered = array_filter($unfiltered, "filter_function");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 2016-01-02
    相关资源
    最近更新 更多