phparraysmultidimensional-arrayfilter

Search for a value in a column of a 2d array and return its first level key


$total = [
    1 => ['title' => 'Jake', 'date' => 'date'],
    2 => ['title' => 'John', 'date' => 'date'],
    3 => ['title' => 'Julia', 'date' => 'date']
];

How to search the title values and return the numeric keys of the qualifying row?

If we search for Julia it should give 3.


Solution

  • Ok sorry for my previous answer, didn't notice it was nested array. You may try this instead:

    function recursiveArraySearch($haystack, $needle, $index = null)
    {
        $aIt   = new RecursiveArrayIterator($haystack);
        $it    = new RecursiveIteratorIterator($aIt);
    
        while($it->valid())
        {
            if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
                return $aIt->key();
            }
    
            $it->next();
        }
    
        return false;
    }
    
    $array = array(3 => array('title' => 'Julia'));
    
    $key = recursiveArraySearch($array, 'Julia');
    echo $key;
    

    Result:

    3