我有2D数组
$array1=[["a1", "a2", "h3", "a4"],["b1", "b2", "l3", "b4"], ["c1", "c2", "o3", "c4"],["d1", "d2", "k3", "d4"]];
$array1=[["b1", "b2", "l3", "b4"], ["a1", "a2", "h3", "a4"], ["d1", "d2", "d3", "d4"], ["c1", "c2", "t3", "c4"]];
Array
(
[0] => Array
(
[0] => a1
[1] => a2
[2] => Array
(
[0] => h3
[1] => h3
)
[3] => a4
)
[1] => Array
(
[0] => b1
[1] => b2
[2] => Array
(
[0] => l3
[1] => l3
)
[3] => b4
)
[2] => Array
(
[0] => c1
[1] => c2
[2] => Array
(
[0] => o3
[1] => t3
)
[3] => c4
)
[4] => Array
(
[0] => d1
[1] => d2
[2] => Array
(
[0] => k3
[1] => d3
)
[3] => d4
)
)
[[a1,a2,a3,a4],[b1,b2,b3,b4]]
[[a1,a2,d3,a4],[b1,b2,e3,b4]]
我希望它们合并,所以最终的数组将是
[[a1,a2,[a3,d3],a4],[b1,b2,[b3,e3],b4]]
到目前为止,我想出了这个,但它对我来说看起来很混乱,有没有其他解决方案如何在3个相同值上合并2D数组呢?
$newArr = [];
foreach($firstArray as $fArray){
foreach($secondArray as $sArray){
if($fArray['first_item'] === $sArray['first_item'] &&
$fArray['second_item'] === $sArray['second_item'] &&
$fArray['fourth_item'] === $sArray['fourth_item']){
$newArr[] = [$farray['first_item'], $fArray['second_item],
[$fArray['third_item'], $sArray['third_item']], $fArray['fourth_item]]
}
}
}
答案 0 :(得分:1)
我已更正您当前的代码以获得所需的输出。我已经更改了您当前在帖子中使用的索引。
<?php
ini_set('display_errors', 1);
$firstArray = [["a1", "a2", "h3", "a4"],["b1", "b2", "l3", "b4"], ["c1", "c2", "o3", "c4"],["d1", "d2", "k3", "d4"]];
$secondArray = [["b1", "b2", "l3", "b4"], ["a1", "a2", "h3", "a4"], ["d1", "d2", "d3", "d4"], ["c1", "c2", "t3", "c4"]];
$result = array();
$newArr = [];
foreach ($firstArray as $fArray)
{
foreach ($secondArray as $sArray)
{
if ($fArray[0] === $sArray[0] && $fArray[1] === $sArray[1] && $fArray[3] === $sArray[3])
{
$newArr[] = [$fArray[0], $fArray[1],
[$fArray[2], $sArray[2]], $fArray[3]];
}
}
}
print_r($newArr);
<强>输出:强>
Array
(
[0] => Array
(
[0] => a1
[1] => a2
[2] => Array
(
[0] => h3
[1] => h3
)
[3] => a4
)
[1] => Array
(
[0] => b1
[1] => b2
[2] => Array
(
[0] => l3
[1] => l3
)
[3] => b4
)
[2] => Array
(
[0] => c1
[1] => c2
[2] => Array
(
[0] => o3
[1] => t3
)
[3] => c4
)
[3] => Array
(
[0] => d1
[1] => d2
[2] => Array
(
[0] => k3
[1] => d3
)
[3] => d4
)
)