Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search associative array by value

Tags:

php

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 instance, the camera model below. Does PHP have any built in methods to search through associative array values and return the matching arrays? In my example below I would like to search for the [label] => Model and get [_content] => NIKON D5100.

Please let me know if you want me to elaborate.

print_r($exif['photo']['exif']); 

Result:

Array (     [0] => Array         (             [tagspace] => IFD0             [tagspaceid] => 0             [tag] => Make             [label] => Make             [raw] => Array                 (                     [_content] => NIKON CORPORATION                 )          )      [1] => Array         (             [tagspace] => IFD0             [tagspaceid] => 0             [tag] => Model             [label] => Model             [raw] => Array                 (                     [_content] => NIKON D5100                 )          )      [2] => Array         (             [tagspace] => IFD0             [tagspaceid] => 0             [tag] => XResolution             [label] => X-Resolution             [raw] => Array                 (                     [_content] => 240                 )              [clean] => Array                 (                     [_content] => 240 dpi                 )          ) 
like image 482
Johan Avatar asked Sep 11 '12 19:09

Johan


People also ask

How do you find the data from an associative array?

Answer: Use the PHP array_values() function You can use the PHP array_values() function to get all the values of an associative array.

How do you find a specific value in an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

Does in_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.

How do you find the element of a multidimensional array?

Multidimensional array search using array_search() method: The array_search() is an inbuilt function which searches for a given value related to the given array column/key. This function only returns the key index instead of a search path.


1 Answers

$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.

like image 96
Arief Hidayatulloh Avatar answered Oct 14 '22 03:10

Arief Hidayatulloh