1

I have this simple array $tree in PHP that I need to filter based on an array of tags matching those in the array.

Array
(
    [0] => stdClass Object
        (
            [name] => Introduction
            [id] => 798162f0-d779-46b6-96cb-ede246bf4f3f
            [tags] => Array
                (
                    [0] => client corp
                    [1] => version 2
                )
        )

    [1] => stdClass Object
        (
            [name] => Chapter one
            [id] => 761e1909-34b3-4733-aab6-ebef26d3fcb9
            [tags] => Array
                (
                    [0] => pro feature
                )
        )
)

I tried using an anonymous function like so:

$selectedTree = array_filter($tree, function($array) use ($selectedTags){
   return in_array($array->tags, $selectedTags, true);
});

$selectedTags:

Array
(
    [0] => client corp
)

The above is returning empty when I'd expect item 1 to be returned. No error thrown. What am I missing?

3
  • I'm sorry, it's a bit unclear what the current behavior is. Is it not working? Is it not filtering it correctly? Is it throwing an exception? Commented Nov 20, 2014 at 23:01
  • @ChrisForrence sorry, it's not filtering (i.e. returning empty). No error thrown. Commented Nov 20, 2014 at 23:02
  • 3
    Your function is searching for $selectedTags in $array->tags, both of which are arrays. in_array() will only return true if the arrays match exactly (same number of elements with the same content). You need to loop through one array, searching for each element in the other array in turn. Commented Nov 20, 2014 at 23:04

2 Answers 2

3

In case of in_array($neddle, $haystack). the $neddle must need to be a String, but you're giving an array that is why its not behaving properly.

But if you like to pass array as value of $selectedTags then you might try something like below:

$selectedTree = array_filter($tree, function($array) use ($selectedTags){
   return count(array_intersect($array->tags, $selectedTags)) > 0;
});

Ref: array_intersect

Sign up to request clarification or add additional context in comments.

Comments

2

If I am reading the question correctly, you need to look at each object in $tree array and see if the tags property contains any of the the elements in $selectedTags

Here is a procedural way to do it.

$filtered = array();
foreach ($tree as $key => $obj) {
    $commonElements = array_intersect($selectedTags, $obj->tags);
    if (count($commonElements) > 0) {
        $filtered[$key] = $obj;
    }
}

I was going to also post the functional way of doing this but, see thecodeparadox's answer for that implementation.

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.