skip to Main Content

I have an array similar to this below. I need to find a way to extract values by using a key/value pair for instance by using 'parent_id' => 3. I want to get all values for said array ( id = 2, label = Content Creation, link_url = '', parent_id = 3 ).

I’ve tried using array_intersect() without any success.

Thank You for your assistance.

Array ( 
    [0] => Array ( [id] => 1 [label] => Web Development [link_url] => [parent_id] => 1 ) 
    [1] => Array ( [id] => 2 [label] => Content Creation [link_url] => [parent_id] => 3 ) 
    [2] => Array ( [id] => 3 [label] => PHP Jobs [link_url] => /simple_link.php [parent_id] => 1 ) 
    [3] => Array ( [id] => 4 [label] => OSCommerce projects [link_url] => /another_link.php [parent_id] => 4 )
)

2

Answers


  1. I thik you can loop in your array and match your desidered parent_id with an if condition

    foreach($array as $data)
    {
        if($data['parent_id'] == '3')
        {
            echo $data['id'] . ' ' . $data['label'] . ' ' . $data['link_url'];
        }
    }
    
    Login or Signup to reply.
  2. You can also use array_filter for these sort of problems

    $matching_results = array_filter($data, function($item) {
       return ($item['parent_id'] == 3);
    });
    

    It will cycle through the data and $matching_results will be an array of each $item that returns true

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search