Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for values in nested array

I have an array as follows

array(2) {
  ["operator"] => array(2) {
    ["qty"] => int(2)
    ["id"] => int(251)
  }
  ["accessory209"] => array(2) {
    ["qty"] => int(1)
    ["id"] => int(209)
  }
  ["accessory211"] => array(2) {
    ["qty"] => int(1)
    ["id"] => int(211)
  }
}

I'm trying to find a way to verify an id value exists within the array and return bool. I'm trying to figure out a quick way that doesn't require creating a loop. Using the in_array function did not work, and I also read that it is quite slow.

In the php manual someone recommended using flip_array() and then isset(), but I can't get it to work for a 2-d array.

doing something like

if($array['accessory']['id'] == 211)

would also work for me, but I need to match all keys containing accessory -- not sure how to do that

Anyways, I'm spinning in circles, and could use some help. This seems like it should be easy. Thanks.

like image 441
dardub Avatar asked Apr 22 '10 18:04

dardub


2 Answers

array_walk() can be used to check whether a particular value is within the array; - it iterates through all the array elements which are passed to the function provided as second argument. For example, the function can be called as in the following code.

function checkValue($value, $key) {
  echo $value['id'];
}

$arr = array(
  'one' => array('id' => 1),
  'two' => array('id' => 2),
  'three' => array('id' => 3)
);

array_walk($arr, 'checkValue');
like image 182
falomir Avatar answered Nov 15 '22 04:11

falomir


This function is useful in_array(211, $array['accessory']); It verifies the whole specified array to see if your value exists in there and returns true.

in_array

like image 45
Jonathan Czitkovics Avatar answered Nov 15 '22 04:11

Jonathan Czitkovics