如何为关联数组创建索引数组?

时间:2014-04-22 21:33:08

标签: php arrays

我有这个多维数组:

$arr = [
2 => ["a", "b", "c"],
5 => ["j", "k", "l"],
9 => ["w", "x", "y", "z"]
];

我想为此创建一个像这样的新索引数组:

$index = [
    "a" => 2,
    "b" => 2,
    "c" => 2,
    "j" => 5,
    "k" => 5,
    "l" => 5,
    "w" => 9,
    "x" => 9,
    "y" => 9,
    "z" => 9
]

我找不到任何看似这样做的PHP函数,但我确定有一个。或者也许有一些已知的代码可以有效地完成这项工作?

1 个答案:

答案 0 :(得分:4)

$index = array();
foreach ($arr as $k => $a) {
  foreach ($a as $v) {
    $index[$v] = $k;
  }
}