PHP search key in array and return its value?
15,028
Solution 1
If all the array keys have the same structure the following code should work:
foreach($array as $item){
$sentat = $item['STATUS'][0]['value'][0][0];
$sample = $item['SAMPLE'][0]['value'][0][0];
}
More detailed information would help us to provide you more tips :)
Solution 2
Please, see if my function works for you:
function get_value_by_key($array,$key)
{
foreach($array as $k=>$each)
{
if($k==$key)
{
return $each;
}
if(is_array($each))
{
if($return = get_value_by_key($each,$key))
{
return $return;
}
}
}
}
Use:
$array = array('array1'=>array('array2'=>array('find_some_key'=>'some_value')));
echo get_value_by_key($array,'find_some_key'); // outputs: some_value
Author by
Aditya Hajare
Punching ducks and patching monkeys. :p Profile: https://github.com/aditya43
Updated on June 04, 2022Comments
-
Aditya Hajare almost 2 years
I would like to search key in multidimensional array and i would like to get corrosponding value associated with that key. For e.g. I would like to extract following texts from below array :
SENT AT 12.08ms
And the text
sample id 41962
following is an array print_r() output :
Array ( [0] => Array ( [VERSION] => Array ( [0] => Array ( [group] => [param] => Array ( ) [value] => Array ( [0] => Array ( [0] => 3.0 ) ) ) ) [SAMPLE] => Array ( [0] => Array ( [group] => [param] => Array ( ) [value] => Array ( [0] => Array ( [0] => sample id 41962 ) ) ) ) [TSAM] => Array ( [0] => Array ( [group] => [param] => Array ( ) [value] => Array ( [0] => Array ( [0] => sample group 141 ) [1] => Array ( [0] => ¯ ) [2] => Array ( [0] => sample batch 81 ) [3] => Array ( [0] => ) [4] => Array ( [0] => ) ) ) ) [STATUS] => Array ( [0] => Array ( [group] => [param] => Array ( [TYPE] => Array ( [0] => CART ) ) [value] => Array ( [0] => Array ( [0] => SENT AT 12.08ms ) ) ) ) ) )
Can somebody provide me optimized code for above problem. The multidimensional array contains more than 5000 to 10000 arrays.