php - PHP 根据对象的值定义数组的键
问题描述
使用 PHP,我有对象列表。每个对象都有id
字段:
$myArray = [
0 => Object{
'id' => 1,
'title' => 'My title 1'
},
1 => Object{
'id' => 2,
'title' => 'My title 2'
},
2 => Object{
'id' => 6,
'title' => 'My title 6'
}
]
我想从id
对象设置数组键而不需要额外的 foreach。我想要这个结果:
$myArray = [
1 => Object{
'id' => 1,
'title' => 'My title 1'
},
2 => Object{
'id' => 2,
'title' => 'My title 2'
},
6 => Object{
'id' => 6,
'title' => 'My title 6'
}
]
我认为这是可能的,array_map
但我不知道该怎么做。我试过了,但它返回子数组:
$newArray = array_map(function($entry) {
return [$entry->id => $entry];
}, $myArray);
// return :
[
0 => [
1 => Object{
'id' => 1,
'title' => 'My title 1'
},
],
1 => [
2 => Object{
'id' => 2,
'title' => 'My title 2'
},
],
2 => [
6 => Object{
'id' => 6,
'title' => 'My title 6'
}
]
]
解决方案
$myArray = array_column($myArray, null, 'id');
推荐阅读
- php - 如何使用 PHP 计算特定页面上的真实访问者数量
- excel - 是否立即声明了电子表格中所有模块中的所有全局变量?
- react-native - React Native“无法打开设置重新映射的类缓存”
- c++ - for循环中的计数器在执行后错误地递增
- android - 更新 gradle ver apk 大小两倍后,为什么?
- python - 字符串格式化和传递
- python - 使用openpyxl更改excel列格式类型
- javascript - 如何取消订阅 React-Native 中的 Firestore 侦听器?
- arrays - 通过调用基于行的 vba 函数来更新工作表中的单元格(范围)
- amazon-s3 - 尝试上传包含用户凭据的 url 时出现“非数字端口”错误