Basically I just would like to know if there is a built-in way of doing this, that might be faster, like maybe with an array_map callback or something:
基本上我只是想知道是否有一种内置的方法,这可能会更快,就像使用array_map回调或其他东西:
function array_rekey($a, $column)
{
$array = array();
foreach($a as $keys) $array[$keys[$column]] = $keys;
return $array;
}
1 个解决方案
#1
1
This should work for you:
这应该适合你:
Just pass NULL
as second argument to array_column()
to get the full array back as values and use $column
as third argument for the keys.
只需将NULL作为第二个参数传递给array_column()以将完整数组作为值返回,并使用$ column作为键的第三个参数。
$result = array_column($arr, NULL, $column);
example input/output:
示例输入/输出:
$arr = [
["a" => 1, "b" => 2, "c" => 3],
["a" => 4, "b" => 5, "c" => 6],
["a" => 7, "b" => 8, "c" => 9],
];
$column = "b";
$result = array_column($arr, NULL, $column);
print_r($result);
output:
输出:
Array
(
[2] => Array
(
[a] => 1
[b] => 2
[c] => 3
)
[5] => Array
(
[a] => 4
[b] => 5
[c] => 6
)
[8] => Array
(
[a] => 7
[b] => 8
[c] => 9
)
)
#1
1
This should work for you:
这应该适合你:
Just pass NULL
as second argument to array_column()
to get the full array back as values and use $column
as third argument for the keys.
只需将NULL作为第二个参数传递给array_column()以将完整数组作为值返回,并使用$ column作为键的第三个参数。
$result = array_column($arr, NULL, $column);
example input/output:
示例输入/输出:
$arr = [
["a" => 1, "b" => 2, "c" => 3],
["a" => 4, "b" => 5, "c" => 6],
["a" => 7, "b" => 8, "c" => 9],
];
$column = "b";
$result = array_column($arr, NULL, $column);
print_r($result);
output:
输出:
Array
(
[2] => Array
(
[a] => 1
[b] => 2
[c] => 3
)
[5] => Array
(
[a] => 4
[b] => 5
[c] => 6
)
[8] => Array
(
[a] => 7
[b] => 8
[c] => 9
)
)