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.
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"
array_keys()
will give you the array's keys. array_values()
will give you the array's values. Both will be indexed numerically.
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
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.
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.