Showing posts with label PHP ARRAY SEARCH. Show all posts
Showing posts with label PHP ARRAY SEARCH. Show all posts

Thursday, 30 August 2018

Recursive search of an array based on the key in php

I need a php function that will recursively search an array on the basis of key I provided. and want to get an array as return output containing all the values those are mapped with the searched key.

For e.g.:
[Case] => Array
    (
        [0] => Array
            (
                [CASE_ID] => 2233
                [CHECK_ID] => 57
                [CLIENT_ID] => 78
            )
        [2] => Array
            (
                [CASE_ID] => 9542
                [CHECK_ID] => 45
                [CLIENT_ID] => 18
            )
     )

If I would pass this array and key CHECK_ID, then it should return me an array containing 57,45. Kindly ask if you need more explanation. Thanks in Advance.

Walking the array and chucking found keys into a new one:
function find_matches($array, $value) {
    $found = array();
    array_walk_recursive($array,
        function ($item, $key) use ($value, &$found) {
            if ($value === $key) {
                $found[] = $item;
            }
        }
    );
    return $found;
}

Have you also considered using find('list') with a fields condition restriction?