associative to numeric array in PHP

北慕城南 提交于 2019-12-24 00:19:06

问题


I have an associative array, which keys I want to use in numbers. What I mean: The array is kinda like this:

$countries = array
    "AD"  =>  array("AND", "Andorra"),
    "BG"  =>  array("BGR", "Bulgaria")
);

Obviously AD is 0 and BG is 1, but when I print $countries[1] it doesn't display even "Array". When I print $countries[1][0] it also doesn't display anything. I have the number of the key, but I shouldn't use the associative key.


回答1:


Perfect use case for array_values:

$countries = array_values($countries);

Then you can retrieve the values by their index:

$countries[0][0]; // "AND"
$countries[0][1]; // "Andorra"
$countries[1][0]; // "BGR"
$countries[1][1]; // "Bulgaria"



回答2:


array_keys() will give you the array's keys. array_values() will give you the array's values. Both will be indexed numerically.




回答3:


you might convert it into a numeric array:

    $countries = array(
    "AD"  =>  array("AND", "Andorra"),
    "BG"  =>  array("BGR", "Bulgaria")
);
$con=array();
$i=0;
foreach($countries as $key => $value){
    $con[$i]=$value;
    $i++;
}
echo $con[1][1];

//the result is Bulgaria



回答4:


There are a couple of workarounds to get what you want. Besides crafting a secondary key-map array, injecting references, or an ArrayAccess abomination that holds numeric and associative keys at the same time, you could also use this:

 print current(array_slice( current(array_slice($countries, 1)), 0));

That's the fugly workaround to $countries[1][0]. Note that array keys appear to appear in the same order still; bemusing.



来源:https://stackoverflow.com/questions/8782368/associative-to-numeric-array-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!