phparraysmultidimensional-arrayfilter

Search a multidimensional array by one column value and return another value from the qualifying row


My array:

Array (
  [friends] => Array (
    [data] => Array ( 
      [0] => Array ( [id] => 1000001823093 [gender] => female [name] => Iri Ghi ) 
      [1] => Array ( [id] => 1000002320316 [gender] => female [name] => Nicole Torn ) 
      [2] => Array ( [id] => 1000003536987 [gender] => female [name] => An Bula ) 
      [3] => Array ( [id] => 1000005923120 [gender] => male [name] => Valent Acc ) 
      [4] => Array ( [id] => 1000008308250 [gender] => female [name] => Dia Apost) 
      [5] => Array ( [id] => 1000008685765 [gender] => female [name] => Mon Nicole )
    )
  )
)

We value 'id: 1000001823093' and I need to search in the array and print 'name: Iri Ghi'.


Solution

  • There are two ways to do this Choose the one that you like

    Method one:

    $find = 1000001823093;
    for($i = 0; $i < count($array['friend']['data']); $i++) {
        if($array['friend']['data'][$i]['id'] == $find) 
            echo $array['friend']['data'][$i]['name'];
    }
    

    Method two:

    $find = 1000001823093;
    foreach($array['friend']['data'] as $data) {
        if($data['id'] == $find)
            echo $data['name'];
    }