多维索引数组到关联数组取决于列值

Gio*_*gio 4 php arrays multidimensional-array

我有一个多维索引数组。每个元素都是一个关联数组,id其中有一列在元素之间是唯一的(它的值在数组中永远不会重复)。

[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
        )
)
Run Code Online (Sandbox Code Playgroud)

我的目标是将这个数组转换为一个多维关联数组,由id值索引。

[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
        )
)
Run Code Online (Sandbox Code Playgroud)

到目前为止,我最好的尝试是遍历数组元素并手动创建最终数组。

$associative = array();
foreach($indexed as $key=>$val) $associative[$val['id']] = $val;
Run Code Online (Sandbox Code Playgroud)

我认为这不是最优雅的解决方案。是否有可能使用内置(更高效)的函数获得相同的结果?

mic*_*usa 6

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.

Code: (Demo)

$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'));
Run Code Online (Sandbox Code Playgroud)

Output:

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,
  ),
)
Run Code Online (Sandbox Code Playgroud)