phparrayssearch

PHP Search Array column for match


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!


Solution

  • 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.