I have this array and I want to combine the y_axis if the x_axis is the same, please see both examples so you will have an idea of what I need.
array:4 [
0 => array:2 [
"x_axis" => 8
"y_axis" => 1
]
1 => array:2 [
"x_axis" => 9
"y_axis" => 1
]
2 => array:2 [
"x_axis" => 11
"y_axis" => 2
]
3 => array:2 [
"x_axis" => 11
"y_axis" => 3
]
]
Like
array:3 [
0 => array:2 [
"x_axis" => 8
"y_axis" => 1
]
1 => array:2 [
"x_axis" => 9
"y_axis" => 1
]
2 => array:2 [
"x_axis" => 11
"y_axis" => 5
]
]
My Answer:
You can achieve this by using a foreach loop to iterate over the array and create a new associative array with the x_axis as the key and the sum of y_axis values as the value. Here's an example code snippet to demonstrate this:
php
$array = [
['x_axis' => 8, 'y_axis' => 1],
['x_axis' => 9, 'y_axis' => 1],
['x_axis' => 11, 'y_axis' => 2],
['x_axis' => 11, 'y_axis' => 3]
];
$result = [];
foreach ($array as $item) {
if (array_key_exists($item['x_axis'], $result)) {
$result[$item['x_axis']] += $item['y_axis'];
} else {
$result[$item['x_axis']] = $item['y_axis'];
}
}
$result = array_map(function($key, $value) {
return ['x_axis' => $key, 'y_axis' => $value];
}, array_keys($result), $result);
print_r($result);
This code will output the desired result:
Array
(
[0] => Array
(
[x_axis] => 8
[y_axis] => 1
)
[1] => Array
(
[x_axis] => 9
[y_axis] => 1
)
[2] => Array
(
[x_axis] => 11
[y_axis] => 5
)
)
Rate this post
3 of 5 based on 4577 votesComments