使用一列作为键、另一列作为值从行数组生成关联数组
我有一个 MySQL 结果集,每行有 2 个值。
每次循环这些结果时,我都想将它们添加到一个数组中。
我希望一个值作为键,另一个作为数组值。
我尝试了这个,但它似乎不起作用:
$dataarray[] = $row['id'] => $row['data'];
如果我有:
$resultSet = [
['id' => 1, 'data' => 'one'],
['id' => 2, 'data' => 'two'],
['id' => 3, 'data' => 'three']
];
我想生成:
[
1 => 'one',
2 => 'two',
3 => 'three'
]
I have a MySQL result set with 2 values in each row.
Each time I loop through these results, I want to add them to an array.
I want one value to be the key, and the other to be the array value.
I tried this, but it doesn't seem to work:
$dataarray[] = $row['id'] => $row['data'];
If I have:
$resultSet = [
['id' => 1, 'data' => 'one'],
['id' => 2, 'data' => 'two'],
['id' => 3, 'data' => 'three']
];
I want to generate:
[
1 => 'one',
2 => 'two',
3 => 'three'
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不直接使用呢
?
Why not just use
?
对于此任务,使用 array_column() 而不是 foreach() 更加优雅/富有表现力/现代/简洁。
另外,array_combine(array_column($array, 'id'), array_column($array, 'data')) 工作得太辛苦,永远不应该使用。
第一个参数是输入行数组。
第二个参数是要成为输出数组中的值的列。
第三个参数是要成为输出数组中的键的列。
代码:(Demo)
输出:
调用集合的 Laravel 等效方法是
pluck()< /code> 类似:
如果您想分配新的一级键但保持行不变,则可以将
null
写入本机函数调用的第二个参数。代码:(演示)
输出:
一种较少实现、无功能的技术是在 无体
foreach()
循环。 (演示)这相当于之前建议的答案:
输出:
It is more elegant/expressive/modern/concise to use
array_column()
instead of aforeach()
for this task.Also,
array_combine(array_column($array, 'id'), array_column($array, 'data'))
is working too hard and should never be used.The first parameter is the input array of rows.
The second parameter is the column to become the values in the output array.
The third parameter is the column to become the keys in the output array.
Code: (Demo)
Output:
The Laravel equivalent method to call on a collection is
pluck()
like:If you'd like to assign new first level keys but leave the rows unchanged, you write
null
as the second parameter of the native function call.Code: (Demo)
Output:
A lesser realized, functionless technique would be to use array destructuring inside a body-less
foreach()
loop. (Demo)This is equivalent to the earlier answers which advise this:
Output: