0

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;
}
1
  • you should add the code wherein you are using it too, add the usage with the input array Commented May 6, 2016 at 2:54

1 Answer 1

1

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
)
Sign up to request clarification or add additional context in comments.

4 Comments

can you add the $array example? It is not working with my array
so please post your array.
@neoDev, I am working on it. try the current script.
@neoDev, Done the script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.