我正在尝试按时间值组合多个数组。我有这样的数组。 我想合并2个数组,我使用array_merge
Array_one :
[
{
date:"2018-06-23",
size:"L",
type:"shoes",
value_one:"66"
},
{
date:"2018-06-23",
size:"XL",
type:"shirt",
value_one:"43"
},
{
date:"2018-06-23",
size:"M",
type:"Bag",
value_one:"23"
}
]
Array_two :
[
{
date:"2018-06-23",
size:"L",
type:"shoes",
value_two:"28"
},
{
date:"2018-06-23",
size:"XL",
type:"shirt",
value_two:"56"
},
{
date:"2018-06-23",
size:"M",
type:"Bag",
value_two:"14"
},
{
date:"2018-06-23",
size:"S",
type:"Cap",
value_two:"29"
}
]
如果索引日期,大小相同,则需要将这2个数组与y值合并,然后键入其合并。例如合并后的数组应该是这样的。
Array_final :
[
{
date:"2018-06-23",
size:"L",
type:"shoes",
value_one:"66",
value_two:"28"
},
{
date:"2018-06-23",
size:"XL",
type:"shirt",
value_one:"43",
value_two:"56"
},
{
date:"2018-06-23",
size:"M",
type:"Bag",
value_one:"23",
value_two:"14"
},
{
date:"2018-06-23",
size:"S",
type:"Cap",
value_one:"null",
value_two:"29"
}
]
在这种情况下我该怎么办? 我想用php,laravel或集合“ Laravel”类解决这种情况。 请帮助我。
答案 0 :(得分:0)
您可以尝试
$Array_final= [];
foreach ($Array_one as $key1 => $value1) {
foreach ($Array_two as $key2 => $value2) {
if ($value1['date']==$value2['date']) {
$Array_final[]=$value2+$value1;
}
}
}
答案 1 :(得分:0)
尝试
//both arrays will be merged including duplicates
$result = array_merge( $array1, $array2 );
//duplicate objects will be removed
$result = array_map("unserialize", array_unique(array_map("serialize", $result)));
//array is sorted on the bases of id
sort( $result );
答案 2 :(得分:0)
尝试
var result = a1.slice(0);
for (var i = 0 ; i < result.length ; i++){
for (var j = 0; j < a2.length ; j++){
if (result[i]. date == a2[j]. date && result[i]. size == a2[j]. size && result[i]. type == a2[j]. type){
result[i]. value_one = a2[j]. value_one;
result[i]. value_two = a2[j].value_two;
}
};
};
console.log(result);
答案 3 :(得分:0)
您可以尝试以下方法:-
$final = $arr1; // default get all values from first array
foreach ($arr2 as $value) { // loop through second array to match
$flag = 0;
foreach ($final as $key => $data) {
// Check for date, size and type
if ($data['date']===$value['date'] && $data['size']===$value['size'] && $data['type']===$value['type']) {
$final[$key]['value_two'] = $value['value_two'];
$flag = 1;
break;
}
}
if ($flag === 0) { // If similar not found, then add new one
array_push($final, $value);
}
}
print_r($final);
输出:-
Array
(
[0] => Array
(
[date] => 2018-06-23
[size] => L
[type] => shoes
[value_one] => 66
[value_two] => 28
)
[1] => Array
(
[date] => 2018-06-23
[size] => XL
[type] => shirt
[value_one] => 43
[value_two] => 56
)
[2] => Array
(
[date] => 2018-06-23
[size] => M
[type] => Bag
[value_one] => 23
[value_two] => 14
)
[3] => Array
(
[date] => 2018-06-23
[size] => S
[type] => Cap
[value_two] => 29
)
)
小提琴链接:-https://3v4l.org/fSh1V