1

I have a PHP array question regarding searching which I'm hoping some kind person can help me with...

The array shown below is an collection of arrays, e.g. order items. As I loop a separate array of orderIds I would like to return the appropriate array of products.

For example, if I request an orderId of 98305 it would return the arrays with the indexes of 2 & 3.

Are there any PHP functions to do this? I could loop each array and check the value and break out when it matches, but I feel this brings quite an overhead of performing multiple loops per orderId lookup.

 Array
 (
     [0] => Array
     (
        [orderId] => 98303
        [product] => Product A
     )

     [1] => Array
     (
        [orderId] => 98304
        [product] => Product B
     )

     [2] => Array
     (
        [orderId] => 98305
        [product] => Product C
     )

     [3] => Array
     (
        [orderId] => 98305
        [product] => Product D
     )

     [4] => Array
     (
        [orderId] => 98306
        [product] => Product A
     )

     [5] => Array
     (
        [orderId] => 98306
        [product] => Product B
     )
 )

Any help appreciated.

D

2
  • I dont know such function. May be it exists. But if your orderId is unique you can use it as a key in array. Then to use isset. Commented Feb 23, 2012 at 22:34
  • That array is very small, I won't care about speed actually. Commented Feb 23, 2012 at 22:34

1 Answer 1

1

array_filter()

$output = array_filter($input,function($a) {
    return $a['orderId'] == 98305;
});

Replace 98305 with the desired ID.

Sign up to request clarification or add additional context in comments.

1 Comment

Good reason to be using it then ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.