我尝试用相同的键将多维数组中的某些值替换为另一个数组 但事实证明是要替换所有值
这是我的示例数组
[
{
"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 map collection并一一地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",
},
]
答案 0 :(得分:1)
函数array_replace_recursive仅用一行代码即可解决您的问题:
从文档中
array_replace_recursive()用以下所有数组中的相同值替换array1的值。如果第二个数组中存在第一个数组中的键,则其值将被第二个数组中的值替换。如果键存在于第二个数组中,而不是第一个数组中,则它将在第一个数组中创建。如果键仅存在于第一个数组中,则将保持不变。如果传递了多个数组进行替换,则将按顺序处理它们,后面的数组将覆盖先前的值。
array_replace_recursive()是递归的:它将递归为数组并将相同的过程应用于内部值。
示例:
$updatedBooks = array_replace_recursive($wrongBooksArray, $correctBooksArray);