ZizouJd
ZizouJd

Reputation: 79

Find values into Array of Object PHP

Hi I have this array of object

[
  {
    "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
    ]
}
]

I want to search in the "categories" array of all objects values in other array and print the match.

Example, I want search the values 222 and 121, values that I push in array

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

And I want search this two values in the result, and print only the object id = 1 and 8774 because are the ones that coincides.

I tested with array_filter into a foreach but doenst works! Any idea? Thanks

This my code

    $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 works but I need print only the Objects that contains the values into a "search" array. Considering that the "search" array can have more than two values

Upvotes: 1

Views: 81

Answers (1)

Barmar
Barmar

Reputation: 781058

array_intersect($array1, $array2) will be truthy if there are any matches between the two arrays. It looks like you only want to select the items that have all the categories in $search. To test that, you need to use

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

DEMO

Also, in general there's no point in writing

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

Just write:

return condition;

So it looks like:

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

Upvotes: 1

Related Questions