假设我有一个关联数组,列出动物园里的动物及其一些功能,比如:
$zoo => array(
"grizzly" => array(
"type" => "Bear",
"legs" => 4,
"teeth" => "sharp",
"dangerous" => "yes"
),
"flamingo" => array(
"type" => "Bird",
"legs" => 2,
"teeth" => "none",
"dangerous" => "no"
),
"baboon" => array(
"type" => "Monkey",
"legs" => 2,
"teeth" => "sharp",
"dangerous" => "yes"
)
);
然后我创建了一个这样的动物列表:
$animal_types = array;
foreach($zoo as $animal) {
$animal_types[] = $animal["type"];
}
哪个输出:
Array(
[0] => "Bear",
[1] => "Bird",
[2] => "Monkey",
)
我希望最后一个数组是这样关联的:
Array(
['grizzly'] => "Bear",
['flamingo'] => "Bird",
['baboon'] => "Monkey",
)
如何使用foreach
从另一个数组中提取数据来创建关联数组?
您只需要在foreach循环中定义键,然后使用第一个数组的当前元素的键,来指定第二个数组上的插入键。类似于:
$animal_types = array();
foreach($zoo as $key=>$animal) {
$animal_types[$key] = $animal["type"];
}
你的意思是:
foreach($zoo as $animal_name => $animal) {
$animal_types[$animal_name] = $animal["type"];
}
$animal_types = array();
foreach($zoo as $aName=>$animal) {
$animal_types[$aName] = $animal["type"];
}
因为您已经有了键,所以只需要更改值。因此,复制动物园并更改每个值:
$animal_types = $zoo;
foreach($animal_types as &$animal) {
$animal = $animal["type"];
}
unset($animal);
或者可能更容易掌握关闭:
$animal_types = array_map(function($v){return $v["type"];}, $zoo);
<?php
# holds the key names - only 4 defined
$key_names = array(
'first',
'second',
'third',
'last'
);
# holds the key values - 6 defined
$values_array = array(
0.93,
null,
true,
'a string here',
'what about this?',
'*'
);
# the new array that will have named keys
$new_array = array();
# used to match the current $values_array item index
# with the corresponding key name from $key_names
$index = 0;
# parse the $values_array
foreach( $values_array as $values_array_entry ) {
# assign the key name if it exists
if( isset($key_names[$index]) ) {
$new_array[ $key_names[$index] ] = $values_array_entry;
} else {
# this covers the case where there are fewer key names than key values
# these keys would receive integer values starting with 0
# using the current index for this example
$new_array[$index] = $values_array_entry;
}
# increment the index by 1 after each pass
$index++;
}
# output the new array
echo '<pre>';
var_dump($new_array);
echo '</pre>';
?>
结果:
array(6) {
["first"]=>
float(0.93)
["second"]=>
NULL
["third"]=>
bool(true)
["last"]=>
string(13) "a string here"
[4]=>
string(16) "what about this?"
[5]=>
string(1) "*"
}