Search code examples
phparraysmultidimensional-arrayfilter

Search for a value in the 3rd level of a 3d array and return the first level key


$list[7362][0]['value'] = 'apple';
$list[7362][1]['value'] = 'orange';
$list[9215][0]['value'] = 'lemon';

I want key for value 'orange'. I tried with array_search() and array_column(), but obviously I have issue array_column().

$key = array_search('orange', array_column($list, 'value'));

as described

Get the first level key of the first row containing a specified column value in a 2d array

but my case is slighly different. Key should return 7362.


Solution

  • You can try something like this:

    <?php
    
    $list = array();
    
    $list[7362][0]['value'] = 'apple';
    $list[7362][1]['value'] = 'orange';
    $list[9215][0]['value'] = 'lemon';
    
    foreach ($list as $keynum=>$keyarr) {
        foreach ($keyarr as $key=>$index) {
            if (array_search('orange', $index) !== false) {
                echo "orange found in $key >> $keynum";
            }   
        }   
    }
    
    ?>
    

    You can choose to just echo out echo $keynum; for your purpose.

    Loop through the arrays and find out where you find orange.

    You can refactor that a bit into a function like this:

    <?php
    
    function getKeys($list, $text) {
        foreach ($list as $keynum=>$keyarr) { 
            foreach ($keyarr as $key=>$index) { 
                if (array_search($text, $index) !== false) {
                    return "$text found in $key >> $keynum";
                }
            }
        }
    
        return "not found";
    }
    
    $list = array();
    
    $list[7362][0]['value'] = 'apple';
    $list[7362][1]['value'] = 'orange';
    $list[9215][0]['value'] = 'lemon';
    
    echo getKeys($list, 'lemon');
    
    ?>
    

    echo getKeys($list, 'lemon'); will give you lemon found in 0 >> 9215.

    echo getKeys($list, 'orange'); will give you orange found in 1 >> 7362.

    echo getKeys($list, 'apple'); will give you apple found in 0 >> 7362.