【问题标题】:Unset variable from php array从 php 数组中取消设置变量
【发布时间】:2020-05-28 11:28:44
【问题描述】:

我有一个数组,当打印出来时,它看起来如下所示,尽管有许多警告和成功消息可用:

Array
(
    [warning] => Array
        (
            [0] => We might have a problem.
            [1] => You might have a problem.
            [2] => They may have a problem.
        )

    [success] => Array
        (
            [0] => Everything is awesome
        )

)

我需要查看数组并找到带有字符串值You might have a problem. 的警告。所以我有以下代码:

foreach($msgArray as $msgType => $messages) {
    foreach($messages as $message => $msg) {
        if($message == 'warning' && $msg == 'You might have a problem.'){
            unset($msgArray[$msgType]);
        }
    }
}

但不幸的是,这会从$msgArray 中删除 all $msgType of warning

我怎样才能删除 just 值为“您可能有问题。”的警告?

谢谢!

【问题讨论】:

  • 你真的要循环2次吗?

标签: php arrays unset


【解决方案1】:

没有循环和比较,一行就可以完成。只需搜索消息以返回密钥和unset它:

unset($msgArray['warning'][array_search('You might have a problem.', $msgArray['warning'])]);

【讨论】:

    【解决方案2】:

    您正在删除顶级密钥。只需删除第二级:

    unset($msgArray[$msgType][$message]);
    

    附:鉴于您显示的数据和代码,$message永远不会成为warning$msgType 会。

    【讨论】:

    • 谢谢@Greg Schmidt - 就是这样。顺便说一句,我的目标是删除 $msgType == 警告的 $message,因此您的代码是正确的,而我的代码一直都是错误的!
    猜你喜欢
    • 2017-05-22
    • 1970-01-01
    • 2011-03-12
    • 2017-10-17
    • 2013-11-12
    • 2012-04-08
    • 2016-10-01
    • 2013-02-17
    相关资源
    最近更新 更多