neoDev neoDev - 7 months ago 20
PHP Question

recursive multiple match in multidimensional php array

I need to match all "keywords" in a multidimesional array:

$array = array(
'green' => 'keyword',
'orange',
'keyword',
'black' => array(
'purple' => 'text',
'brown',
'pink' => 'keyword'
),
'white' => array(
'red',
'yellow' => 'keyword',
'blue'
),
'violet',
'gray'
);


Then I would like to access the match results like:

$matches[0][0]
$matches[2]
$matches[3][2]
....


What should I use? I tried with array_filter but doesn't work.. also it might have to be recursive

function findInArray($array){
$array = array_filter($array, function($array){
return ($array == 'keyword');
});
return $array;
}

Answer

You can did the thing by using array_filter.

Online check 3v4l.org

$arr = array();

$str = 'keyword';
$arr[] = array_filter($array, function($var) use ($str) {
            global $arr;
            if(is_array($var)){             
                $arr[] = array_filter($var, function($var2) use ($str) {
                    return preg_match("/$str/i", $var2);
                });
            }else{
                return preg_match("/$str/i", $var);
            }           
        });

function getL2Keys($array){
    $result = array();
    foreach($array as $sub) {
        $result = array_merge($result, $sub);
    }        
    return $result;
}

$arr = getL2Keys($arr);

Result:

Array
(
    [pink] => keyword
    [yellow] => keyword
    [green] => keyword
    [0] => keyword
)