PHP join 2 arrays of same key value
PHP join 2 arrays of same key value
I'm wondering how to solved this. I have 3(three) arrays that contained nested values in the "data" key like this:
array:3 [
0 => array:3 [
"status" => "Terkirim"
"warna" => "lightgreen"
"data" => array:12 [
0 => 0
1 => 0
2 => 0
3 => 0
4 => 0
5 => 0
6 => 3
7 => 0
8 => 0
9 => 0
10 => 0
11 => 0
]
]
1 => array:3 [
"status" => "Selesai"
"warna" => "lightblue"
"data" => array:12 [
0 => 0
1 => 0
2 => 0
3 => 0
4 => 0
5 => 0
6 => 3
7 => 0
8 => 0
9 => 0
10 => 0
11 => 0
]
]
2 => array:3 [
"status" => "Selesai"
"warna" => "lightblue"
"data" => array:12 [
0 => 0
1 => 0
2 => 0
3 => 0
4 => 0
5 => 0
6 => 0
7 => 1
8 => 0
9 => 0
10 => 0
11 => 0
]
]
]
My problem is how to join the "data" just if the "status" is the same?, or sum the the value if it already exists on the same index key, this is what I want to achieve:
array:3 [
0 => array:3 [
"status" => "Terkirim"
"warna" => "lightgreen"
"data" => array:12 [
0 => 0
1 => 0
2 => 0
3 => 0
4 => 0
5 => 0
6 => 3
7 => 0
8 => 0
9 => 0
10 => 0
11 => 0
]
]
1 => array:3 [
"status" => "Selesai"
"warna" => "lightblue"
"data" => array:12 [
0 => 0
1 => 0
2 => 0
3 => 0
4 => 0
5 => 0
6 => 3
7 => 1 <== the joined value
8 => 0
9 => 0
10 => 0
11 => 0
]
]
]
Any helps would be appreciated... :)
2 Answers
2
You can do it this way:
$joinedArray = ;
for ($initialArray as $array) {
if (array_key_exists($array['status'], $joinedArray) {
for ($joinedArray['data'] as $key, $dataElement) {
$joinedArray['data'][$key] = $dataElement + $array['data'][$key];
}
} else {
$joinedArray[$array['status']] = $array;
}
}
You can use array_reduce()
to summarize the array into an associative array. Use array_values()
to convert the associative array into a simple array.
array_reduce()
array_values()
$arr = //Your array
$result = array_values(array_reduce($arr, function($c, $v){
if ( !isset( $c[ $v['status'] ] ) ) $c[ $v['status'] ] = $v;
else foreach( $c[ $v['status'] ]['data'] as $key => &$val ) $val += $v['data'][$key];
return $c;
}, array()));
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[0] => Array
(
[status] => Terkirim
[warna] => lightgreen
[data] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 3
[7] => 0
[8] => 0
[9] => 0
[10] => 0
[11] => 0
)
)
[1] => Array
(
[status] => Selesai
[warna] => lightblue
[data] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 3
[7] => 1
[8] => 0
[9] => 0
[10] => 0
[11] => 0
)
)
)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
it works with little modifications, you safe my day :) thank you
– Pirman Dwiana
Jul 1 at 7:01