I'm trying to combine multiple arrays by time values. I have an array like this.
[
{
x:"Kasa",
y:" 8",
id:6,
a:0.019444444444444
},
{
x:"Kasa",
y:" 9",
id:6,
a:0.023611111111111
},
{
x:"Kasa",
y:"10",
id:6,
a:0.018055555555556
},
{
x:"Kasa",
y:"11",
id:6,
a:0.025
},
{
x:"Kasa",
y:"12",
id:6,
a:0.0097222222222222
}
],
[
{
x:"Kasap",
y:" 8",
id:7,
a:0.0013888888888889
},
{
x:"Kasap",
y:" 9",
id:7,
a:0.015277777777778
},
{
x:"Kasap",
y:"10",
id:7,
a:0.0027777777777778
},
{
x:"Kasap",
y:"11",
id:7,
a:0.0041666666666667
},
{
x:"Kasap",
y:"12",
id:7,
a:0.019444444444444
}
]
I need the combine this 2 array with y values. For example After combine the arrays should be like this.
[
{
x:"Kasa",
y:" 8",
id:6,
a:0.019444444444444
},
{
x:"Kasap",
y:" 8",
id:7,
a:0.0013888888888889
}
],
[
{
x:"Kasa",
y:"11",
id:6,
a:0.025
},
{
x:"Kasap",
y:"11",
id:7,
a:0.0041666666666667
}
],
[
{
x:"Kasa",
y:"12",
id:6,
a:0.0097222222222222
},
{
x:"Kasap",
y:"12",
id:7,
a:0.019444444444444
}
],
[
{
x:"Kasa",
y:" 9",
id:6,
a:0.023611111111111
},
{
x:"Kasap",
y:" 9",
id:7,
a:0.015277777777778
}
],
[
{
x:"Kasap",
y:"10",
id:7,
a:0.0027777777777778
},
{
x:"Kasa",
y:"10",
id:6,
a:0.018055555555556
}
]
what should I do for this case ?
由于您将这个问题标记为“ Laravel”,因此可以使用出色的Collection类:
collect($array)->flatten(1)->groupBy('y')->toArray()
Try this: I have tested it with this array
array:3 [▼
0 => array:2 [▼
"x" => "Kasaa"
"y" => "8"
]
1 => array:2 [▼
"x" => "Pasa"
"y" => "9"
]
2 => array:2 [▼
"x" => "tasa"
"y" => "8"
]
]
EDIT
$array= array_merge($array1, $array2);
foreach ($array as $k => $value) {
foreach ( $value as $key => $v) {
if ($key === 'y'){
$result[$v]='';
}
}
}
foreach ($array as $k => $value) {
if ($value['y'] == key_exists($value['y'],$result)) {
$result[$value['y']][$k]= $value;
}
}
Try php built in array_merge_recursive() function
$array = array_merge_recursive($array1, $array2);
or make your own function (it may be faster)
function my_array_merge(&$array1, &$array2) {
$result = Array();
foreach($array1 as $key => &$value) {
$result[$key] = array_merge($value, $array2[$key]);
}
return $result;
}
$array = my_array_merge($array1, array2);
print_r($array);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.