多维索引数组到关联数组,具体取决于列值 [英] Multidimensional indexed array to associative array depending on column value
问题描述
我有一个多维索引数组.每个元素都是一个带有 id
列的关联数组,该列在元素之间是唯一的(其值永远不会在数组中重复).
I have a multidimensional indexed array. Each element is an associative array with an id
column which is unique between elements (its value never repeats within the array).
[indexed] =>Array
(
[0] => Array
(
[id] => john
[name] => John
[age] => 29
),
[1] => Array
(
[id] => peter
[name] => Peter
[age] => 30
),
[2] => Array
(
[id] => harry
[name] => Harry
[age] => 19
)
)
我的目标是将该数组转换为多维关联数组,并由 id
值索引.
My goal is to convert this array into a multidimensional associative array, indexed by id
values.
[indexed] =>Array
(
[john] => Array
(
[id] => john
[name] => John
[age] => 29
),
[peter] => Array
(
[id] => peter
[name] => Peter
[age] => 30
),
[harry] => Array
(
[id] => harry
[name] => Harry
[age] => 19
)
)
到目前为止,我最好的尝试是遍历数组元素并手动创建最终数组.
My best attempt so far is to loop over array elements and manually create the final array.
$associative = array();
foreach($indexed as $key=>$val) $associative[$val['id']] = $val;
我认为这不是最优雅的解决方案.内置的(更有效的)功能是否可以获得相同的结果?
I think it's not the most elegant solution. Is it possible to obtain the same result with built-in (more efficient) functions?
推荐答案
事实是 php确实提供了一个单一的本机函数,可让您用单个列的值替换外部索引.魔术"位于第二个参数中,该参数告诉php在分配新键时不要触摸子数组值.
The truth is php DOES offer a single, native function that allows you to replace the outer indexes with the values of a single column. The "magic" is in the 2nd parameter which tells php not to touch the subarray values when assigning the new keys.
代码:(演示)
$indexed = [
['id' => 'john', 'name' => 'John', 'age' => 29],
['id' => 'peter', 'name' => 'Peter', 'age' => 30],
['id' => 'harry', 'name' => 'Harry', 'age' => 19],
];
var_export(array_column($indexed, null, 'id'));
输出:
array (
'john' =>
array (
'id' => 'john',
'name' => 'John',
'age' => 29,
),
'peter' =>
array (
'id' => 'peter',
'name' => 'Peter',
'age' => 30,
),
'harry' =>
array (
'id' => 'harry',
'name' => 'Harry',
'age' => 19,
),
)
这篇关于多维索引数组到关联数组,具体取决于列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!