我正在使用PHP,我正在使用此处列出的数组: https://gist.github.com/aghouseh/3926213
所以基本上它是一个带有州名的数组,在这些州名中是一个县的列表,如下所示:
$counties = array(
"Alabama" => array(
"Autauga County",
"Baldwin County",
"Barbour County",
"Bibb County")
"California => array(
"Los angeles County",
"San francisco county"));
基本上我想要完成的是:
$counties = array(
"Alabama" => array(
"Autauga County" => "Autauga County",
"Baldwin County" => "Baldwin County",
"Barbour County" => "Barbour County",
"Bibb County" => "Bibb County")
"California => array(
"Los angeles County" => "Los angeles County",
"San francisco county" => "San francisco county"));
我想把第二级数组变成一个关联数组。 我试图寻找答案,我想出了这个,但没有奏效:
foreach ($counties as $state) {
foreach ($state as $county) {
array_combine($county, $county);
}
}
答案 0 :(得分:1)
根据需要创建一个新数组,并用它替换原始数据:
foreach ($counties as $state => $x) {
$c = array();
foreach ($x as $county) {
$c[$county] = $county;
}
$counties[$state] = $c;
}
答案 1 :(得分:1)
实际上array_combine
将是一种优雅而优雅的方式。如果只有你在正确的水平使用它并将其结果存储在某个地方!请注意,array_combine
在原始数组上不能通过引用工作。它返回结果。使用此:
foreach($counties as &$states) {
$states = array_combine($states, $states);
}
这就是完成这项工作所需的所有代码。