phparraysmultidimensional-arrayfilter

Filter a 2d array to only keep rows with two specified column values


I have a PHPArray :

$fullData = array ( 
        array ( 'id' => 23123, 'name'=>'a', number =>...),
            array()....
);

This full dataset is displayed to the user. However if he comes from a form page, I POST data to alter this array.

I need to search the array fields, with respect to the user fields. So if any POST data if not filled, I default the value to all.

if( $resetData == 1) {
    foreach ($params as $i=>$k) {
        if($k!='all') {
            $fields[][$i] = $k;
        }
    }...

Thus getting the user filled data in the fields array. Now how do I search the data filled be the user, in an SQL AND format. example : name == 'aaditi' AND profile == 'student', would list out all data with the names aaditi that have the student profile

I tried various functions like array_search and strstr, and some other questions on stackoverflow, but they are mostly restricted to a single key value search.


Solution

  • I would search the data array line by line finding all those things that match the passed filters. Taking your field array to be a key=>value where key is the column name and value is the wanted value,

    $outputArray = array();
    foreach($fullData as $row) {
        $addToOutput = true;
        foreach ($fields as $field) {
            foreach($field as $key => $value) {
                if (!isset($row[$key]) || $row[$key] != $value) {
                    $addToOutput = false;
                }
            }
        }
        if ($addToOutput == true) {
            $outputArray[] = $row;
        }
    }
    

    It isn't the most efficient solution and I am sure that a better one could be found, but this should work ok at least for not rediculously huge sets of data (>100,000 rows with 10 columns apiece). You could also run this same algorithm with no parameters and all the data should come out.