1

I have a nested array and I was wondering how can I look for an element in it.

Here is the array:

$test = [
    ['item_id' => 780, 'quantity' => 1],
    ['item_id' => 759, 'quantity' => 3],
    ['item_id' => 453, 'quantity' => 12]
];

I did manage to use a foreaech loop but was wondering if there is a better approach?

foreach($test as $t) {
    if($t['item_id']==780) echo $t['quantity'];
}
Ali
  • 2,993
  • 3
  • 19
  • 42
Vivian Kennedy
  • 121
  • 1
  • 8
  • Is `item_id` unique in the array? If it is, you could amend the data structure so it is keyed on that value, and then quantity lookups will just be reduced to an array index. – halfer Jul 06 '15 at 18:32

2 Answers2

0

If the array was already sorted, you could do it in O(log n) time, but if not, you will have to search all elements until you find it, which is O(n) time. If the array is not sorted, I think iterating over them is the only way. If the option exists to pre-sort the array, it could be faster.

Edit: If it was possible to change the data structure, then that would open up a lot of possibilities for a faster algorithm, but I assume that's not the case here.

Tim S.
  • 2,187
  • 1
  • 25
  • 40
0

Use in_array recursively:

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
    return false;
}

$arr = array(array('item_id'=>2132,'quantity'=>1),array('item_id'=>759,'quantity'=>3),array('item_id'=>453,'quantity'=>12));
echo in_array_r("2132", $arr) ? 'found' : 'not found';
Daniel Li
  • 287
  • 2
  • 17