检查数组PHP中是否有一个具有特定值的键

时间:2018-11-24 23:31:56

标签: php arrays

我在这里有这个数组:

Array (
  [0] => stdClass Object (
     [id] => 1
     [message] =>
     [pinned] => 0
  )
  [1] => stdClass Object (
     [id] => 3
     [message] =>
     [pinned] => 1
  )
)

现在我有问题。我需要在此数组中检查该数组中的 [固定] 键之一是否包含值1

如果可以正确回答,我想做点什么。如果不是,请执行下一步。这是一个尝试,但是不起作用:

if (isset($my_array(isset($my_array->pinned)) === 1) {
    //One value of the pinned key is 1
} else {
    //No value of the pinned key is 1 -> skip
}

5 个答案:

答案 0 :(得分:2)

您可以使用array_reduce

if (array_reduce($my_array, function ($c, $v) { return $c || $v->pinned == 1; }, false)) {
    //One value of the pinned key is 1
} else {
    //No value of the pinned key is 1 -> skip
}

Demo on 3v4l.org

答案 1 :(得分:2)

您将需要遍历数组并分别测试每个对象。您可以使用普通循环或flexbox来做到这一点,例如:

array_filter

答案 2 :(得分:1)

通过数组的基本循环

for($i=0;$i<count($arr);$i++){
  if($arr[$i]->pinned==1){
     // it is pinned - do something

  }else{
     // it isn't pinned - do something else/nothing

  }
}

如果您希望在不固定的情况下不做任何事情,只需完全忽略else{}

答案 3 :(得分:1)

draw

您可以使用$ key来找到它。或使用

    $tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(7, 8, 9))
);

foreach ($tmpArray as $inner) {

    if (is_array($inner)) {
        foreach ($inner[1] as $key=>$value) {
           echo $key . PHP_EOL;
        }
    }
}

找到需要的东西。

答案 4 :(得分:1)

尝试一下。

使用search()函数在每个对象中寻找所需的属性,然后检查结果。这是原始代码,可以写出10倍更好的代码,但这仅仅是为了理解。

<?php
$my_array = [
0 => (object) [
    'id' => 1,
    'message' => 'msg1',
    'pinned' => 0
],
1 => (object) [
    'id' => 3,
    'message' => 'msg3',
    'pinned' => 1
  ],
];

/**
 * Search in array $arrayVet in the attribute $field of each element (object) the value $value
 */
function search($arrayVet, $field, $value) {
    reset($arrayVet);
    while(isset($arrayVet[key($arrayVet)])) {
        if($arrayVet[key($arrayVet)]->$field == $value){
            return key($arrayVet);
        }
        next($arrayVet);
    }
    return -1;
}

$pinnedObject = search($my_array, 'pinned', 1);
if($pinnedObject != -1) {
    //One value of the pinned key is 1
    echo $my_array[$pinnedObject]->message;
} else {
    //No value of the pinned key is 1 -> skip
    echo "not found";
  }
?>