search associative array by value

后端 未结 7 2053
感动是毒
感动是毒 2020-12-09 15:40

I\'m fetching some JSON from flickrs API. My problem is that the exif data is in different order depending on the camera. So I can\'t hard-code an array number to get, for i

相关标签:
7条回答
  • 2020-12-09 16:19

    This would be fairly trivial to implement:

    $model = '';
    
    foreach ($exif['photo']['exif'] as $data) {
        if ($data['label'] == 'Model') {
            $model = $data['raw']['_content'];
            break;
        }
    }
    
    0 讨论(0)
  • 2020-12-09 16:22
    $key = array_search('model', array_column($data, 'label'));
    

    In more recent versions of PHP, specifically PHP 5 >= 5.5.0, the function above will work.

    0 讨论(0)
  • 2020-12-09 16:22

    The following function, searches in an associative array both for string values and values inside other arrays. For example , given the following array

     $array= [  "one" => ["a","b"],
                "two" => "c" ];
    

    the following function can find both a,b and c as well

     function search_assoc($value, $array){
             $result = false;
             foreach ( $array as $el){
                 if (!is_array($el)){
                     $result = $result||($el==$value);
                 }
                 else if (in_array($value,$el))
                     $result= $result||true;
                 else $result= $result||false;
             }
             return $result;
         }
    
    0 讨论(0)
  • 2020-12-09 16:24

    As far as I know , PHP does not have in built-in search function for multidimensional array. It has only for indexed and associative array. Therefore you have to write your own search function!!

    0 讨论(0)
  • 2020-12-09 16:27

    $key = array_search('Model', array_map(function($data) {return $data['label'];}, $exif))

    The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function. In this case we are returning the label.

    The array_search() function search an array for a value and returns the key. (in this case we are searching the returned array from array_map for the label value 'Model')

    0 讨论(0)
  • 2020-12-09 16:38
    foreach($exif['photo']['exif'] as $row) {
        foreach ($row as $k => $v) {
            if ($k == "label" AND $v == "Model")
                $needle[] = $row["raw"];
        }
    }
    print_r($needle);
    
    0 讨论(0)
提交回复
热议问题