Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Search Array column for match

Tags:

arrays

php

search

I have an array as below, which has multiple columns. I want to search in the first column for a specific value, and have the rows that match returned. Is that possible to do?

For example:

Array (
[0] => Array ( [id] => 1 [column2] => value2 [column3] => value3 [column4] => value4 [column5] => value5 ) 
[1] => Array ( [id] => 1 [column2] => value2 [column3] => value3 [column4] => value4 [column5] => value5 ) 
[2] => Array ( [id] => 2 [column2] => value2 [column3] => value3 [column4] => value4 [column5] => value5 
)

So let's say I want to search the "id" column for "1" and have the results displayed. How can this be done? Thank you so much!

like image 553
David Avatar asked Jun 28 '14 19:06

David


3 Answers

If you are using PHP >= 5.5, then you can use the new array_column(), in conjunction with array_keys() and array_map().

Given your array, $array:

$keys = array_keys(array_column($array, 'id'), 1);
$new_array = array_map(function($k) use ($array){return $array[$k];}, $keys);

See demo

like image 61
Mark Miller Avatar answered Oct 19 '22 22:10

Mark Miller


Since you have an nested Array you need two iterations:

$filtered = array();
$rows = Your Array;
foreach($rows as $index => $columns) {
    foreach($columns as $key => $value) {
        if ($key == 'id' && $value == '1') {
            $filtered[] = $columns;
        }
    }
}

This should do the job.

like image 35
Mario Werner Avatar answered Oct 20 '22 00:10

Mario Werner


I found a much simpler solution that I think is worthwhile sharing with the world

in_array(1, array_column($yourArray, 'id'));

Tested on PHP >= 5.5

like image 45
MontrealDevOne Avatar answered Oct 20 '22 00:10

MontrealDevOne