我有两个数组:
I need to extend the Sub-Arrays in $postings_array [A]
by merging them
with the Sub-Arrays of the $usersdata_array [B]
based on WHERE the VALUE of the usrsID KEY in the sub-array[A] is EQUAL to the usrsID KEY in the sub-array[B].
示例:Array [A]:
(
[0] => Array
(
[ID] => 5
[usrsID] => 3
[tid] => 19
[txtid] => 22
)
[1] => Array
(
[ID] => 6
[usrsID] => 1
[tid] => 19
[txtid] => 23
)
[2] => Array
(
[ID] => 7
[usrsID] => 2
[tid] => 19
[txtid] => 24
)
[3] => Array
(
[ID] => 8
[usrsID] => 1
[tid] => 19
[txtid] => 25
)
)
--
Array [B]:
(
[0] => Array
(
[id] => 1
[usrsID] => 1
[avatarID] => 1
)
[1] => Array
(
[id] => 2
[usrsID] => 2
[avatarID] => 3
)
[2] => Array
(
[id] => 3
[usrsID] => 3
[avatarID] => 22
)
)
所需结果(上面示例中的 [B] 扩展 [A]):
Array [A_extended]:
(
[0] => Array
(
[ID] => 5
[usrsID] => 3
[tid] => 19
[txtid] => 22
[id] => 3
[avatarID] => 22
)
[1] => Array
(
[ID] => 6
[usrsID] => 1
[tid] => 19
[txtid] => 23
[id] => 1
[avatarID] => 1
)
[2] => Array
(
[ID] => 7
[usrsID] => 2
[tid] => 19
[txtid] => 24
[id] => 2
[avatarID] => 3
)
[3] => Array
(
[ID] => 8
[usrsID] => 1
[tid] => 19
[txtid] => 25
[id] => 1
[avatarID] => 1
)
)
...我认为,这是一个常见问题,因此应该有一种最佳实践(可能是一个内置 PHP 函数或其中两个或三个函数的组合) - 而且我不必重新发明轮子.
否则,我的方法是
接近, 与 hayStackArray = 完整的 [A]Array; 针 = [B] 子数组的 $usrsID 值:检查迭代量(= $usersdata_array [B] 中找到的子数组)
- 迭代outerHaystack并在innerHaystack中找到$needle时触发函数
- 通过 checkSubArrayfunc 执行合并
function checkSubArrayfunc($hayStackSubArray, $needle, $toMergeSubArray) {
if (in_array(array('$hayStackSubArray'), $needle)) {
array_merge_recursive($hayStackSubArray, $toMergeSubArray);
}
}
foreach($arr_b as $b_item) {
foreach($arr_a as $key => &$a_item) {
if ($b_item['usrsID'] == $a_item['usrsID']) {
$a_item['id'] = $b_item['usrsID'];
$a_item['avatarID'] = $b_item['avatarID'];
}
}
}
您的
$_arr_a
的输出将是:
Array
(
[0] => Array
(
[ID] => 5
[usrsID] => 3
[tid] => 19
[txtid] => 22
[id] => 3
[avatarID] => 22
)
[1] => Array
(
[ID] => 6
[usrsID] => 1
[tid] => 19
[txtid] => 23
[id] => 1
[avatarID] => 1
)
[2] => Array
(
[ID] => 7
[usrsID] => 2
[tid] => 19
[txtid] => 24
[id] => 2
[avatarID] => 3
)
[3] => Array
(
[ID] => 8
[usrsID] => 1
[tid] => 19
[txtid] => 25
[id] => 1
[avatarID] => 1
)
)
userID 相同,则将这些数组合并并推入 margeArr。
$margeArr = [];
foreach($Array_A as $a){
foreach($Array_B as $b){
if($a['usrsID'] == $b['usrsID']){
array_push($margeArr,array_merge($a,$b));
}
}
}
print_r($margeArr);
问卷评论: 这是一个很好的解决方案 - 它确实满足了我的问题中描述的要求,并将要标记的数组与“要注入”数组的键值对合并。 但我更喜欢世界上最好的程序员的解决方案,在那里我可以将键重命名为“en passant / on-the-fly”:
foreach($arr_b as $b_item) {
foreach($arr_a as $key => &$a_item) {
if ($b_item['usrsID'] == $a_item['usrsID']) {
$a_item['myNewKeyName1'] = $b_item['usrsID'];
$a_item['myNewKeyName2'] = $b_item['avatarID'];
}
}
}
print("<pre>".print_r($arr_a,true)."</pre>");
$lookup = array_column($arrayB, null, 'usrsID');
foreach ($arrayA as $row) {
$result[] = $row + ($lookup[$row['usrsID']] ?? []);
}
break
。