1

So i need to return the number (6, 8 or 10) with the country value. So in the example, with 'sweden' its supposed to return 8 but the key of the array is apparently just Array(). Is the wrong in the structure of my array or the usage of array_keys?

$list= array (
  'list' => 
  array (
    6 => 
    array (
        'default',
        'finland'
    ),
    8 => 
    array (
        'sweden',
        'norway'
    ),
    10 => 
    array (
        'germany',
        'belgia'
    ),
  ),
);
print_r(array_keys($list, "sweden"));

return: Array()

40oz
  • 45
  • 8
  • Possible duplicate of [PHP Multidimensional Array Searching (Find key by specific value)](https://stackoverflow.com/questions/8102221/php-multidimensional-array-searching-find-key-by-specific-value) – René Höhle Jan 01 '19 at 01:26
  • doesnt look to be – 40oz Jan 01 '19 at 01:28
  • What? use the accepted Answer that is working ;) `arrray_keys` isn't working with multidimensional arrays very well. – René Höhle Jan 01 '19 at 01:29
  • in that question its an associative array and is looking for 'slug' with slugs value, this is different – 40oz Jan 01 '19 at 01:32

3 Answers3

3

You have two problems.

First, the array you want to search is $list['list'], not $list itself.

Second, the second argument to array_keys() is only useful for 1-dimensional arrays. You have a 2-dimensional array, but array_keys() will not automatically search inside the nested arrays. So you need to write your own loop or use array_filter().

$results = array();
foreach ($list['list'] as $key => $value) {
    if (array_search('sweden', $value) !== false) {
        $results[] = $key;
    }
}
print_r($results);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

use foreach for it.

foreach ($list as $key => $value){

}
PHP Geek
  • 3,949
  • 1
  • 16
  • 32
0

I think this is what you want

foreach($list as $key => $value ){  
        $arr = array_keys($value);//this has your (6, 8 or 10)         
        foreach($arr as $val){
             print_r($value[$val]);//showing array data of 6,8,10 indexes
        }  
    }

output: enter image description here

Khagesh
  • 191
  • 1
  • 11