我尝试用具有相同键的另一个数组替换多维数组中的某些值 但结果却替换了所有值
这是我的示例数组
[
{
"book_id": 45,
"language_code": "RUWT-EN",
"book_name": Study,
"country": "Singapore",
"created_by": 12,
"created_date": "2019-04-09 09:19:24",
"update_by": 12,
"update_date": "2019-06-25 03:57:52",
"status": "1",
},
{
"book_id": 46,
"language_code": "RUWT-EN",
"book_name": Sleep,
"country": "Indonesia",
"created_by": 12,
"created_date": "2019-04-09 09:19:24",
"update_by": 12,
"update_date": "2019-06-25 03:57:52",
"status": "1",
},
{
"book_id": 47,
"language_code": "RUWT-EN",
"book_name": Teaching,
"country": "China",
"created_by": 12,
"created_date": "2019-04-09 09:19:24",
"update_by": 12,
"update_date": "2019-06-25 03:57:52",
"status": "1",
},
]
这是我的第二个数组
[
{
"book_id": 45,
"language_code": "RUWT-CH",
"book_name": Study in CH,
"country": "Korea",
"status": "2",
},
{
"book_id": 46,
"language_code": "RUWT-CH",
"book_name": Sleep in CH,
"country": "US",
"status": "2",
},
{
"book_id": 47,
"language_code": "RUWT-CH",
"book_name": Teaching in CH,
"country": "England",
"status": "2",
},
]
我尝试过使用 laravel 地图集合并 foreach 一个一个的值,然后替换具有相同键的值,但它太长了。我想 最简单的方法
$result = $collect_real->map(function($item) use($lang){
return $item['book_name'] = $lang->where('book_id', $item['book_id'])->values();
});
我想要这样的结果
[
{
"book_id": 45,
"language_code": "RUWT-CH",
"book_name": Study in CH,
"country": "Korea",
"created_by": 12,
"created_date": "2019-04-09 09:19:24",
"update_by": 12,
"update_date": "2019-06-25 03:57:52",
"status": "2",
},
{
"book_id": 46,
"language_code": "RUWT-CH",
"book_name": Sleep in CH,
"country": "US",
"created_by": 12,
"created_date": "2019-04-09 09:19:24",
"update_by": 12,
"update_date": "2019-06-25 03:57:52",
"status": "2",
},
{
"book_id": 47,
"language_code": "RUWT-CH",
"book_name": Teaching in CH,
"country": "England",
"created_by": 12,
"created_date": "2019-04-09 09:19:24",
"update_by": 12,
"update_date": "2019-06-25 03:57:52",
"status": "2",
},
]
函数array_replace_recursive用一行代码解决了您的问题:
来自文档:
array_replace_recursive() 将 array1 的值替换为以下所有数组中的相同值。如果第一个数组中的键存在于第二个数组中,则其值将被第二个数组中的值替换。如果该键存在于第二个数组中,而不是第一个数组中,则它将在第一个数组中创建。如果某个键仅存在于第一个数组中,则它将保持原样。如果传递多个数组进行替换,它们将按顺序处理,后面的数组会覆盖前面的值。
array_replace_recursive() 是递归的:它将递归到数组并对内部值应用相同的过程。
示例:
$updatedBooks = array_replace_recursive($wrongBooksArray, $correctBooksArray);