从 php 数组中取消设置变量

Unset variable from php array

我有一个数组,打印出来时看起来像下面这样,尽管有许多警告和成功消息可用:

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

如何删除 只是 值为 "You might have a problem." 的警告?

谢谢!

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

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

P.S。根据您显示的数据和代码,$message 永远不会 成为 warning$msgType 会。

一行就可以完成,无需循环和比较。只需搜索 return 密钥和 unset 的消息:

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