【问题标题】:how can i check if key exists with certain value inside a foreach php array我如何检查在foreach php数组中是否存在具有特定值的键
【发布时间】:2017-08-23 11:41:30
【问题描述】:

嗨,我有 php 数组,它总是如下所示。我正在使用 foreach。所以我想检查值 01 的键 $value['month'] 是否存在。我的意思是$value['month'] 将永远存在,但我要检查的是。是否存在一定的价值。

Array
(
[0] => Array
    (
        [label] => 03
        [value] => 2
    )

[1] => Array
    (
        [label] => 05
        [value] => 2
    )

[2] => Array
    (
        [label] => 06
        [value] => 12
    )

[3] => Array
    (
        [label] => 07
        [value] => 12
    )

[4] => Array
    (
        [label] => 08
        [value] => 1
    )

)

【问题讨论】:

  • 因此使用foreach 进行迭代并检查。有什么问题?
  • 顺便说一句,您的数组中没有键 month
  • 换句话说这就是我想要的foreach ($result as $key => $value) { //if $value['label'] exists with value 01 then do something //in other words if this exists //Array ( [0] => Array ( [label] => 01 [value] => 2 )) }
  • 然后呢?你有什么问题?
  • @u_mulder 我的意思是标签而不是月份。我刚刚在上面做了我的 foreach,但我不知道如何检查..请看上面的 cooment

标签: php arrays loops foreach


【解决方案1】:

使用foreach() 进行迭代并比较:

// whatever the corresponding label should be
$label = '01';

foreach ($data as $key => element) {
    if (is_array($element) 
        && array_key_exists('label', $element)
        && '01' === $element['label']
    ) {
        // found matching element with $key
    }
}

或者,使用array_walk() 进行迭代:

// whatever the corresponding label should be
$label = '01';

array_walk($data, function (array $element) use ($label) {
    if (array_key_exists('label', $element) && $label === $element['label']) {
        // found matching element
    }
});

或者,如果您想过滤并查找匹配元素的数组,请使用array_filter()

// whatever the corresponding label should be
$label = '01';

$matching = array_filter($data, function (array element) use ($label) {
    return array_key_exists('label', $element) && $label === $element['label']
}); 

if (0 !== count($matching)) {
    // found at least once in $data
}

参考见:

【讨论】:

  • 这项工作很完美..但是如果我只想了解标签而不担心什么是“价值”我感兴趣的是是否存在具有特定价值的标签?你打算怎么过?
  • 让我为你调整一下。
  • 有机会再看一遍吗?
猜你喜欢
  • 2018-06-15
  • 2018-07-02
  • 1970-01-01
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-25
  • 2011-05-29
相关资源
最近更新 更多