1

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

3
  • php.net/manual/en/function.array-intersect.php Commented Jan 19, 2017 at 0:55
  • array_filter should work. Show your code so we can tell you what you did wrong. Commented Jan 19, 2017 at 0:56
  • Edited @Barmar. Array filter works but array_intersect that I have not work for me but I want the objects that contains the values in search array Commented Jan 19, 2017 at 1:11

1 Answer 1

1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.