簡體   English   中英

在 PHP 對象數組中查找值

[英]Find values into Array of Object PHP

嗨,我有這個對象數組

[
  {
    "id": 1,
    "categories": [
      222,
      243,
      208,
      115,
      173,
      253,
      236,
      121,
      69,
      250,
      221,
      270,
      245,
      123,
      124
    ]
},
{
    "id": 2,
    "categories": [
      222,
      243,
      208,
      69,
      250,
      221,
      270,
      245,
      123,
      124
    ]
},{
    "id": 8774,
    "categories": [
      222,
      243,
      208,
      115,
      173,
      253,
      236,
      121
    ]
}
]

我想在其他數組中所有對象值的“類別”數組中搜索並打印匹配項。

例如,我想搜索值222121 ,我推入數組的值

$array = ("222","121");

我想在結果中搜索這兩個值,並只打印對象 id = 1 和 8774,因為它們是重合的。

我用 array_filter 在 foreach 中進行了測試,但確實有效! 任何的想法? 謝謝

這是我的代碼

    $search = array("231","228");
    $result = array_filter($array, function ($item) use ($search) {
        if (array_intersect($item["categories"], $search)) {
            return true;
        }
        return false;
    });
//$array is the array of object result

Array_intersect 有效,但我只需要將包含值的對象打印到“搜索”數組中。 考慮到“搜索”數組可以有兩個以上的值

如果兩個數組之間有任何匹配,則 array_intersect array_intersect($array1, $array2)將是真實的。 看起來您只想選擇具有$search所有類別的項目。 要測試它,您需要使用

if (count(array_intersect($item["categories"], $search)) == count($search))

演示

此外,一般來說,寫作是沒有意義的

if (condition) {
    return true;
} else {
    return false;
}

寫就好了:

return condition;

所以它看起來像:

$result = array_filter($array, function ($item) use ($search) {
    return count(array_intersect($item["categories"], $search)) == count($search);
});

暫無
暫無

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

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