简体   繁体   中英

how to get multidimentional associate array keys in one array?

I have array dataand every array has its own values in array too As below :

$array['loc']=array('india','usa','germany');   
$array['loc1']=array('india','usa','germany');      
$array['loc2']=array('india','usa','germany');      
$array['loc3']=array('india','usa','germany');      
$array['loc4']=array('india','usa','germany');   

I want key list in one array like below:

$list['keys']=array('loc','loc1','loc2','loc3');

You can use array_keys

$array = [];
$array['loc']=array('india','usa','germany');   
$array['loc1']=array('india','usa','germany');      
$array['loc2']=array('india','usa','germany');      
$array['loc3']=array('india','usa','germany');      
$array['loc4']=array('india','usa','germany');   

$list['keys'] = $keys = array_keys($array);
print_r($list['keys']);

array_keys — Return all the keys or a subset of the keys of an array

Demo .

Output

Array
(
    [0] => loc
    [1] => loc1
    [2] => loc2
    [3] => loc3
    [4] => loc4
)

You can use PHP's array_keys method like so:

array_keys($array)

This will give you an array of all your locations. As you want an array $list array of these keys, you can build your array using:

$list["keys"] = array_keys($array)

See example below:

$array['loc']=array('india','usa','germany');   
$array['loc1']=array('india','usa','germany');      
$array['loc2']=array('india','usa','germany');      
$array['loc3']=array('india','usa','germany');      
$array['loc4']=array('india','usa','germany');   

$list["keys"] = array_keys($array);

print_r($list["keys"]);

Output :

Array ( [0] => loc [1] => loc1 [2] => loc2 [3] => loc3 [4] => loc4 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM