我有两个学生和标记。需要一个marks_sheet之类的输出数组。删除marks数组中不存在的所有数据,并插入一个新的字段marks。 //此数组的名称学生
Array
(
[0] => Array
(
[userId] => user1
[name] => Suman Mandal
[age] => 20
)
[1] => Array
(
[userId] => user2
[name] => Amit Halder
[age] => 30
)
[2] => Array
(
[userId] => user3
[name] => Asif Rahman
[age] => 25
)
[3] => Array
(
[userId] => user4
[name] => Gopal Ghosh
[age] => 21
)
)
//此数组的名称标记
Array
(
[0] => Array
(
[userId] => user1
[marks]=>80
)
[1] => Array
(
[userId] => user3
[marks]=>90
)
)
我需要这样的输出: //此数组的名称 marks_sheet
Array
(
[0] => Array
(
[userId] => user1
[name] => Suman Mandal
[age] => 20
[marks]=>80
)
[1] => Array
(
[userId] => user3
[name] => Asif Rahman
[age] => 25
[marks]=>90
)
)
我对php有一点了解。也许这很简单,但是我很难解决...请帮助我
答案 0 :(得分:0)
您可以在userId
索引数组上使用array_replace_recusrive
。
首先使用array_column
通过userId
索引数组。
然后使用array_replace_recursive
合并数组中的值并保留两个数组集的键索引。
最后使用array_intersect_key
仅从$marks
数组返回数组值。
$students = array_column($students, null, 'userId');
$marks = array_column($marks, null, 'userId');
$marks_sheet = array_intersect_key(array_replace_recursive($students, $marks), $marks);
结果
Array
(
[user1] => Array
(
[userId] => user1
[name] => Suman Mandal
[age] => 20
[marks] => 80
)
[user3] => Array
(
[userId] => user3
[name] => Asif Rahman
[age] => 25
[marks] => 90
)
)
如果您不希望最终结果被userId
索引,则可以使用array_values
,它将为数组重新索引。
$marks_sheet = array_values(
array_intersect_key(array_replace_recursive($students, $marks), $marks)
);
结果
Array
(
[0] => Array
(
[userId] => user1
[name] => Suman Mandal
[age] => 20
[marks] => 80
)
[1] => Array
(
[userId] => user3
[name] => Asif Rahman
[age] => 25
[marks] => 90
)
)
或者,您可以遍历标记和学生以构建marks_sheet数组。
$marks_sheet = [];
foreach ($marks as $mark) {
foreach ($students as $student) {
if ($student['userId'] === $mark['userId']) {
$mark_sheet = $student;
foreach ($mark as $key => $value) {
$mark_sheet[$key] = $value;
}
$marks_sheet[] = $mark_sheet;
}
}
}
结果
Array
(
[0] => Array
(
[userId] => user1
[name] => Suman Mandal
[age] => 20
[marks] => 80
)
[1] => Array
(
[userId] => user3
[name] => Asif Rahman
[age] => 25
[marks] => 90
)
)