问题描述一:
比如有个变量($stu_list)的值为下面的数组,然后把数组里的id这个键值提出来组成一个新的集合
目标数组:
Array
(
[0] => Array
(
[id] => 1
[group_id] => 5,3
[cTime] => 2021-03-02 09:29:37
[people_count] => 179
)
[1] => Array
(
[id] => 2
[group_id] => 2
[cTime] => 2021-03-02 09:36:27
[people_count] => 123
)
[2] => Array
(
[id] => 3
[group_id] => 5,8
[cTime] => 2021-03-02 09:41:05
[people_count] => 163
)
[3] => Array
(
[id] => 5
[group_id] => 6
[cTime] => 2021-03-02 09:44:21
[people_count] => 299
)
)
需要的结果:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
以下方法都可实现上述效果
解决方案:
方法1:
array_map (仅对获取第一列值有效)
$id_arr = array_map('array_shift', $stu_list);
方法2:
使用 array_column 函数,不过此函数需要 PHP 版本要求,(PHP 5 >= 5.5.0)
$id_arr = array_column($stu_list, 'id');
方法3:
使用array_reduce函数,此方法配合create_function,但这个函数似乎已被弃用。
用法:
$id_arr = array_reduce($stu_list, create_function('$v,$w', '$v[]=$w["id"];return $v;'));
问题描述二:
php 如何把数组中某个键值取出作为数组的键名,怎么实现
例如把下面的数组$list1里的username这个键值作为最外层的键名
原数据:
Array
(
[0] => Array
(
[id] => 105
[username] => 张学友
[cTime] => 2021-03-02 09:44:21
[people_count] => 299
)
[1] => Array
(
[id] => 106
[username] => 刘德华
[cTime] => 2021-03-02 09:44:21
[people_count] => 299
)
[2] => Array
(
[id] => 107
[username] => 郭富城
[cTime] => 2021-03-02 09:44:21
[people_count] => 299
)
)
需要的结果: 提取username 或者提取id
Array
(
[张学友] => Array
(
[id] => 105
[username] => 张学友
[cTime] => 2021-03-02 09:44:21
[people_count] => 299
)
[刘德华] => Array
(
[id] => 106
[username] => 刘德华
[cTime] => 2021-03-02 09:44:21
[people_count] => 299
)
[郭富城] => Array
(
[id] => 107
[username] => 郭富城
[cTime] => 2021-03-02 09:44:21
[people_count] => 299
)
)
以下两种方法都可以得到上述结果。
方法1:可以用foreach()循环
foreach ($list1 as $k => $v) {
$list1[$v['username']] = $v;
unset($list1[$k]);
}
方法2:可以用php的内置函数:array_column()
$list1 = array_column($list1,null,'username');
|