php - 如何通过在 php 中映射值来组合两个数组?
问题描述
我有两个数组 $a 和 $b
$a = [
'0' => [
'name'=>'Apple',
'id' => 1
],
'1' => [
'name'=>'Banana',
'id' => 2
],
'2' => [
'name' => 'orange',
'id' => 3
]
];
和
$b = [
'0' => [
'price'=> 20,
'a_id' => 2
],
'1' => [
'price'=> 10,
'a_id' => 3
],
'3' => [
'price'=> 30,
'a_id' => 1
]
];
我正在尝试使用 id(array $a), a_id (array $b) 映射创建另一个数组,我的输出看起来像
$a = [
'0' => [
'id' => 1
'name'=>'Apple',
'price' => 30
],
'1' => [
'id' => 2
'name'=>'Banana',
'price' => 20
],
'2' => [
'id' => 3
'name' => 'orange',
'price' => 10
]
];
我试过数组映射
$combined = array_map(null,$a,$b);
但是这个结果不是我想要的结果。如何在匹配后将我的第一个数组映射到第二个数组$a['id'] = $b['a_id']
?
解决方案
这应该有效,如果数组 $b 中的项目没有价格,则将添加默认价格 0。
<?php
$result = [];
$t = array_column($b, 'a_id');
foreach($a as $k => $v) {
$index = array_search($v['id'], $t);
$v['price'] = $index !== FALSE ? $b[$index]['price'] : 0;
$result[] = $v;
}
print_r($result);
?>
结果:
(
[0] => Array
(
[name] => Apple
[id] => 1
[price] => 30
)
[1] => Array
(
[name] => Banana
[id] => 2
[price] => 20
)
[2] => Array
(
[name] => orange
[id] => 3
[price] => 10
)
)
推荐阅读
- java - 在eclipse中将一个Maven项目作为一个现有项目中的子项目导入
- python - 熊猫将列表分解为列
- javascript - Firebase firestore 分页返回重复的结果
- flutter - 如何隐藏flutter应用程序的url?
- jquery - 请求正文为空,POST 节点 js ajax 调用 json Web 令牌
- c# - .NET Core Worker 服务没有 CRON
- windows - 关闭数据库连接后脚本退出时 Perl 崩溃
- amazon-s3 - 对除 1 个文件夹之外的所有操作的 AWS S3 存储桶的完全访问权限
- html - 在我的 Angular 项目中包含引导样式时出错
- bash - Azure Office 365 管理 API