【问题标题】:Php compare external value to array value if matched [duplicate]如果匹配,Php将外部值与数组值进行比较[重复]
【发布时间】:2019-08-11 18:20:09
【问题描述】:

我有这个数组 ($item):

Array
        (

            [categoria] => Array
                (
                    [0] => Array
                        (
                            [tid] => 6737
                            [name] => Sala VIP
                            [endereco] => 
                            [logo] => 
                            [image] => 
                            [link] => /taxonomy/term/6737
                            [site] => 
                            [color] => 
                            [peso] => 0
                            [icone] => 1
                            [url_emissores] => 
                        )

                )

            [destaque] => 1
        )

我想比较$something 是否等于[name] => Sala VIP。我怎样才能做到这一点?我正在尝试:

if($something == $item[categoria][0].name) {
   #code
}

【问题讨论】:

  • $item['categoria'][0]['name']
  • @Jonnix 谢谢人
  • @Jonnix 真的有必要在单词之间使用''吗?不能只是 $item[categoria][0][name] 吗?
  • @VitorMascia 它可以工作,但我不推荐它。如果没有引号,它将首先尝试使用带有这些名称的常量,而不是将它们视为字符串。为了 2',只需要使用显式字符串即可。
  • @VitorMascia - 你可以使用它,但你会收到警告。 Use of undefined constant foo assuming 'foo' 或类似的东西。

标签: php arrays php-7


【解决方案1】:

如上所述,您可以访问数组的索引,例如['someIndex']。但是如果这个数组不是一个常量,你应该确保这个字段确实被设置了,否则你会得到一个未定义的索引错误。

在比较之前添加isset() 可以防止此类错误:

if(isset($item['categoria'][0]['name']) && $item['categoria'][0]['name'] === $something) {
   #code
}

希望对你有帮助,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2015-11-17
    相关资源
    最近更新 更多