Aru*_*ven 1 php arrays indexing multidimensional-array
我从查询中得到了这个数组。
Array
(
[0] => Array
(
[user_id] => 5
[first_name] => Diyaa
[profile_pic] => profile/user5.png
)
[1] => Array
(
[user_id] => 8
[first_name] => Raj
[profile_pic] => profile/user8.jpg
)
[2] => Array
(
[user_id] => 10
[first_name] => Vanathi
[profile_pic] => profile/user10.jpg
)
)
Run Code Online (Sandbox Code Playgroud)
我需要将数组索引设置为如下所示的数组值( user_id
):
Array
(
[5] => Array
(
[user_id] => 5
[first_name] => Diyaa
[profile_pic] => profile/user5.png
)
[8] => Array
(
[user_id] => 8
[first_name] => Raj
[profile_pic] => profile/user8.jpg
)
[10] => Array
(
[user_id] => 10
[first_name] => Vanathi
[profile_pic] => profile/user10.jpg
)
)
Run Code Online (Sandbox Code Playgroud)
注: user_id
为唯一值,不再重复。无需担心索引值。
如何转换并获取该数组作为指定的索引值..?
这正是array_column()
用于:
$result = array_column($array, null, 'user_id');
Run Code Online (Sandbox Code Playgroud)
array_column() 返回输入的单个列中的值,由 column_key 标识。可选地,可以提供 index_key 以通过来自输入数组的 index_key 列的值索引返回数组中的值。
列键
要返回的值列。该值可能是您希望检索的列的整数键,也可能是关联数组或属性名称的字符串键名称。返回完整数组或对象也可能为 NULL(这与 index_key 一起重新索引数组很有用)。
你可以试试这个代码,我在这里做一些额外的工作。请参阅AbraCadaver 的巧妙回答$result = array_column($array, null, 'user_id');
。
array_combine(array_column($array, 'user_id'), $array);
Run Code Online (Sandbox Code Playgroud)