PHP multidimensional array search by value

前端 未结 23 3222
情歌与酒
情歌与酒 2020-11-21 04:45

I have an array where I want to search the uid and get the key of the array.

Examples

Assume we have the following 2-dimensional array:

<
23条回答
  •  北海茫月
    2020-11-21 05:37

    I modified one of examples below description function array_search. Function searchItemsByKey return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:

     $arr = array(
         'XXX'=>array(
                   'YYY'=> array(
                        'AAA'=> array(
                              'keyN' =>'value1'
                       )
                   ),
                  'ZZZ'=> array(
                        'BBB'=> array(
                              'keyN' => 'value2'
                       )
                   )
                  //.....
               )
    );
    
    
    $result = searchItemsByKey($arr,'keyN');
    
    print '
    ';
    print_r($result);
    print '
    ';
    // OUTPUT
    Array
    (
      [0] => value1
      [1] => value2
    )
    

    Function code:

    function searchItemsByKey($array, $key)
    {
       $results = array();
    
      if (is_array($array))
      {
        if (isset($array[$key]) && key($array)==$key)
            $results[] = $array[$key];
    
        foreach ($array as $sub_array)
            $results = array_merge($results, searchItemsByKey($sub_array, $key));
      }
    
     return  $results;
    }
    

提交回复
热议问题