Merging two multidimensional arrays on specific key(在特定键上合并两个多维数组)
本文介绍了在特定键上合并两个多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下数组:
Array
(
[0] => Array
(
[id] => 5
[name] => Education
)
[1] => Array
(
[id] => 4
[name] => Computers
)
[3] => Array
(
[id] => 7
[name] => Science
[4] => Array
(
[id] => 1
[name] => Sports
)
)
第二个:
Array
(
[0] => Array
(
[id] => 1
[title] => Sport
)
[1] => Array
(
[id] => 7
[title] => Sci
)
[3] => Array
(
[id] => 4
[title] => Comp
[4] => Array
(
[id] => 5
[title] => Edu
)
)
所需的输出是:
Array
(
[0] => Array
(
[id] => 5
[name] => Education
[title] => Edu
)
[1] => Array
(
[id] => 4
[name] => Computers
[title] => Comp
)
[3] => Array
(
[id] => 7
[name] => Science
[title] => Sci
[4] => Array
(
[id] => 1
[name] => Sports
[title] => Sport
)
)
我已经设法将这些数组与简单地合并:
I have managed to merge these arrays with simply:
foreach($first as $key => $value){
$result[$key] = array_merge($first[$key], $second[$key]);
}
但是输出没有正确组合:
But the output is not combined correctly:
Array
(
[0] => Array
(
[id] => 5
[name] => Education
[title] => Sport
)
[1] => Array
(
[id] => 4
[name] => Computers
[title] => Sci
)
[3] => Array
(
[id] => 7
[name] => Science
[title] => Comp
[4] => Array
(
[id] => 1
[name] => Sports
[title] => Edu
)
)
问题是我想在相同的 id
上合并这些数组.所需的输出排序应与第一个数组中的排序相同.
The problem is I would like to merge these arrays on the same id
.
Desired output sorting should be same as in the first array.
我怎样才能做到这一点?非常感谢任何帮助.
How can I achieve this? Any help is much appreciated.
推荐答案
你可以做一个嵌套循环并检查 id
值是否匹配,然后将 title
添加到$first
(或 name
到 $second
)
You can just do a nested loop and check if the id
values match, then add title
to $first
(or name
to $second
)
foreach($first as $key => $value){
foreach($second as $value2){
if($value['id'] === $value2['id']){
$first[$key]['title'] = $value2['title'];
}
}
}
这篇关于在特定键上合并两个多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在特定键上合并两个多维数组
基础教程推荐
猜你喜欢
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01