2 回答
TA贡献1783条经验 获得超4个赞
// create a version of $a that uses the member_id as key, makes look-up easier
$a_reindexed = array_combine( array_column($a, 'member_id'), array_values($a) );
// get the current maximum sorting value from the elements in $a
$max_sort = max(array_column($a, 'sorting'));
$result = [];
// add values from $b to the result
foreach($b as $key => $value) {
$result[$key] = $value;
// set the sorting property to that of the corresponding element from $a_reindexed
// or PHP_INT_MAX if the former doesn’t exist
$result[$key]['sorting'] = $a_reindexed[$value['member_id']]['sorting'] ?? PHP_INT_MAX;
}
// sort the result array by the sorting value, so all elements with PHP_INT_MAX will go to the end
usort($result, function($a, $b) { return $a['sorting'] <=> $b['sorting']; });
// set new sorting value for all items having it set to PHP_INT_MAX
foreach($result as $key => $value) {
if($value['sorting'] == PHP_INT_MAX) {
$result[$key]['sorting'] = ++$max_sort;
}
}
TA贡献1772条经验 获得超6个赞
可能适合您需求的基本解决方案:
/*
* first, store all records with matching member_id into store $c
*/
$c = [];
foreach ($b as $key0 => $value0) {
foreach ($a as $key1 => $value1) {
// matching 'member_id'?
if ($value0['member_id'] === $value1['member_id']) {
// inject record into store $c
$c[] = $a[$key1];
}
}
}
/*
* second, inject non-matching records from $b into store $c
*/
$ids = array_column($c, 'member_id');
foreach ($b as $key => $value) {
if (!in_array($value['member_id'], $ids)) {
$sorting = max(array_column($c, 'sorting')) + 1;
$value['sorting'] = $sorting;
$c[] = $value;
}
}
工作演示
- 2 回答
- 0 关注
- 165 浏览
添加回答
举报