I have PHP array of arrays as below and I want to extract the arrays based on key "type" value. I mean for example in the below code want to extract based on
'type' => '1'
'type' => '2' ( There are two arrays for this condition)
'type' => '22' ( There are two arrays for this condition)
For this I am going each element in the for loop and combing the related ones . But is there any direct function available to do this ?
some thing like array.search(type value 2) giving the related two entries ..? ( because I have lot of types like this )
Thanks for your help
array
0 =>
array
'type' => string '1'
'code' => string '1'
'total_count' => string '200'
'car_count' => string '4'
1 =>
array
'type' => string '2'
'code' => string '52160'
'total_count' => string '100'
'car_count' => string '2'
2 =>
array
'type' => string '2'
'code' => string '26'
'total_count' => string '30'
'car_count' => string '15'
3 =>
array
'type' => string '20'
'code' => string '6880'
'total_count' => string '4'
'car_count' => string '0'
4 =>
array
'type' => string '21'
'code' => string '256'
'total_count' => string '10'
'car_count' => string '5'
5 =>
array
'type' => string '22'
'code' => string '20'
'total_count' => string '100'
'car_count' => string '8'
6 =>
array
'type' => string '22'
'code' => string '25'
'total_count' => string '120'
'car_count' => string '9'
You can formulate your condition inside a function that returns
true
if an array element matches andfalse
if not.You then use it as a callback with
array_filter
Docs.Example (type must be integer 2):
Modify the function according to your needs. The input will be a single element.
Or if you prefer some interface on your array to be called with a specified constraint (Demo):
But a more elegant variant would be to use a FilterIterator on the array that can take the arguments far nicer and is much more re-useable (Demo):