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

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

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

https://stackoverflow.com/questions/7423181/

相关文章:

asp.net - Rad Ajax 加载面板未显示在 asp.net 页面的回发中

vim - 你如何在 Vim 中删除除特定模式之外的所有内容?

ruby-on-rails - Rails formtastic 自动为表单输入创建无序列表

iphone - 为什么重力比例在 box2d 中不起作用

image - 修改或添加 dicom 标签

r - 是否有一个 R 包可以处理 POSIX 对象并返回一周的第 n 个 N 日?

haskell - 与 Word8 和 Int 相关的类型错误

css - 调整 HTML map 图像的大小

django - 更改各种对象的 django-tinymce 内容 css

c# - 小数精度 - C#