array( "type" => "Bear", -6ren">
gpt4 book ai didi

php - 使用 foreach 创建 PHP 关联数组时如何为键分配名称?

转载 作者:行者123 更新时间:2023-12-05 09:24:58 27 4
gpt4 key购买 nike

假设我有一个关联数组,其中列出了动物园里的动物及其一些特征,如下所示:

$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"];
}

关于php - 使用 foreach 创建 PHP 关联数组时如何为键分配名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7423181/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com