0
  array(  
    [n] => array(

       [mother]   => 'some_name',
       [children] =>  [n] => array(
                               ['child_name']=>'some_name'
                               ...
                             )

         )
   )

I would like to filter this array using the array_filter(). To filter that array to get only the "records" where the mothers are named "Jane" for instance I do the following which is working like a charm.

array_filter($myarray, function ($k) { 
   return $k['mother'] == 'Jane'; 
});

Now I would like to filter $myarray to get the "records" where the children are named "Peter". I tried the following which is not working.

array_filter($myarray, function ($k) { 
    return $k['children']$k['child_name'] == 'Peter'; 
});

I also tried the following which is not working either.

array_filter($myarray, function ($k1,$k2) { 
    return $k1['children']$k2['child_name'] == 'Peter'; 
});
4
  • array([child_name] => ...) is invalid syntax. What does the array actually look like? Commented Feb 24, 2014 at 16:21
  • It's print_r() output I guess Commented Feb 24, 2014 at 16:22
  • I redited myarray so you can better see how it is composed... Commented Feb 24, 2014 at 16:29
  • I don;t know that array_filter is what you are looking for here since you are needing to use both a key and a value. You may have a look at array_walk() or array_walk_recursive(), or simply just build your own looping logic in a function. it is also not clear what you want to happen when the key/value is found in child array. Should that child array itself be filtered? Commented Feb 24, 2014 at 16:59

1 Answer 1

3

You have an error inside the array filter callback function:

$myarray = array(
    array(
       'mother'   => 'Jane',
       'children' =>  array(
            array('child_name' => 'Peter'),
            array('child_name' => 'Peter2')
        )
    ),

    array(
       'mother'   => 'Jane1',
       'children' =>  array(
            array('child_name' => 'Peter1'),
        )
    )
);

//The filtering
$myarray = array_filter($myarray, function ($k) {

    //Loop through childs
    foreach ($k['children'] AS $child)
    {
        //Check if there is at least one child with the required name 
        if ($child['child_name'] === 'Peter')
            return true;
     }

    return false;
});

print_r($myarray);
Sign up to request clarification or add additional context in comments.

1 Comment

Hello. Already tried not working because [children] is an array. The are usually multiple children. So the question is how to use multiple keys in the callback function?

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.