我有一个关联数组,我想要使用数字作为键。我的意思是:这个数组大致长这样:
$countries = array
"AD" => array("AND", "Andorra"),
"BG" => array("BGR", "Bulgaria")
);
显然,AD是0,BG是1,但当我打印
$countries[1]
时,它甚至不显示"Array"
。
当我打印$countries[1][0]
时,也没有显示任何内容。我有键的编号,但不应使用关联键。我有一个关联数组,我想要使用数字作为键。我的意思是:这个数组大致长这样:
$countries = array
"AD" => array("AND", "Andorra"),
"BG" => array("BGR", "Bulgaria")
);
$countries[1]
时,它甚至不显示"Array"
。
当我打印$countries[1][0]
时,也没有显示任何内容。我有键的编号,但不应使用关联键。array_values
的完美应用场景:
$countries = array_values($countries);
然后,您可以通过它们的索引来检索值:
$countries[0][0]; // "AND"
$countries[0][1]; // "Andorra"
$countries[1][0]; // "BGR"
$countries[1][1]; // "Bulgaria"
$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
有几种方法可以实现你想要的功能。除了制作一个次要的键映射数组、注入引用或者使用一个同时持有数字和关联键的ArrayAccess
怪物,你还可以使用以下方法:
print current(array_slice( current(array_slice($countries, 1)), 0));
这是对$countries[1][0]
的丑陋解决方法。请注意,数组键似乎仍然以相同的顺序出现;令人困惑。
AD
是0
”并不那么明显。甚至可能不是真的? - Kerrek SB