我有一个来自数据库查询的数组:
Array (
[0] => Array ( [div_id] => 21 [div_name] => "Alphabet" )
[1] => Array ( [div_id] => 16 [div_name] => "Elementary" )
[2] => Array ( [div_id] => 19 [div_name] => "Preschool" )
[3] => Array ( [div_id] => 20 [div_name] => "Secondary" )
)
我想将其转换为:
Array (
[21] => "Alphabet"
[16] => "Elementary"
[19] => "Preschool"
[20] => "Secondary"
)
但是,我无法使用密钥名称。我需要将它们作为第一列和第二列引用,因为在我的上下文中我无法控制源数据的键。我需要对具有不同键名的数据使用相同的算法,例如:
Array (
[0] => Array ( [unknown_id] => 21 [random] => "Alphabet" )
[1] => Array ( [unknown_id] => 16 [random] => "Elementary" )
[2] => Array ( [unknown_id] => 19 [random] => "Preschool" )
[3] => Array ( [unknown_id] => 20 [random] => "Secondary" )
)
这个问题与Convert array of key-value pairs into associative array非常相似,但是密钥有[0]和[1],我有文本键,但仍然需要引用数组的第一项和第二项。
答案 0 :(得分:3)
你可以这样做:
$indexed = array_map('array_values', $data);
$res = array_combine(array_column($indexed, 0), array_column($indexed, 1));
或者使用array_column
的第三个参数:
$res = array_column(array_map('array_values', $data), 1, 0);
答案 1 :(得分:2)
实际上有一个内置函数可以做到这一点。使用第三个参数按特定列索引数组:
$result = array_column($array, 'div_name', 'div_id');
{p <1}}需要PHP&gt; = 5.5.0或使用PHP Implementation of array_column()
答案 2 :(得分:1)
因为在不可预测的键上使用功能编程会导致不必要的卷积和过多的迭代。您应该使用经典的foreach()
循环来设置新的数据结构。
代码:(Demo)
$array = [
["unknown_id1" => 21, "randomA" => "Alphabet"],
["unknown_id2" => 16, "randBom" => "Elementary"],
["unknown_id3" => 19, "raCndom" => "Preschool"],
["unknown_id4" => 20, "Drandom" => "Secondary"]
];
foreach ($array as $row) {
$result[current($row)] = end($row);
}
var_export($result);
输出:
array (
21 => 'Alphabet',
16 => 'Elementary',
19 => 'Preschool',
20 => 'Secondary',
)