0
$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

PHP multidimensional array search by value

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

adpo
  • 9
  • 5

2 Answers2

1

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.

zedfoxus
  • 35,121
  • 5
  • 64
  • 63
0

It's nested to far for the array_column at that level, so just loop:

foreach($list as $k => $v) {
    if(in_array('orange', array_column($v, 'value'))) {
        $key = $k;
        break;
    }
}

If there can be more than one then create an array and don't break:

        $key[] = $k;
        //break;
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87