簡體   English   中英

檢查在Array PHP中是否存在具有特定值的鍵

[英]Check if there is a key which has a specific value in Array PHP

我在這里有這個數組:

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

現在我有一個問題。 如果此數組中的某個鍵[pinned]包含值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
}

你可以使用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
}

在3v4l.org上演示

您需要迭代數組並單獨測試每個對象。 你可以使用普通循環或array_filter來做到這array_filter ,例如:

$pinnedItems = array_filter($my_array, function($obj) {
  return $obj->pinned === 1;
});
if (count($pinnedItems) > 0) {
  // do something
}

通過數組的基本循環

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{}

    $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;
        }
    }
}

您可以使用$ key來查找它。 或者使用

$key = array_search ('your param', $arr);

找到你需要的東西。

嘗試這個。

使用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";
  }
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM