I have two arrays
First array named "$periods" and second array named "$groupExport" like below.
Array
(
[0] => 201308
[1] => 201309
[2] => 201310
)
Array
(
[0] => Array
(
[GroupCode] => 111
[GroupDesc] => Crop Production
[201308] => 1.5500
[201309] => 240.4200
[201310] => 41.2110
)
[1] => Array
(
[GroupCode] => 112
[GroupDesc] => Animal Production
[201309] => 3.1800
)
[2] => Array
(
[GroupCode] => 115
[GroupDesc] => Agriculture, Forestry Support
[201308] => 234.0400
[201310] => 343.0200
)
)
I have tried atleast 5-6 different code ideas, it does not yields the below output. I want the output like below, so that I can display the resultset in table format according to the header GroupCode, GroupDesc, 201308, 201309 & 201310. Could anyone help me to resolve this?
Array
(
[0] => Array
(
[GroupCode] => 111
[GroupDesc] => Crop Production
[201308] => 1.5500
[201309] => 240.4200
[201310] => 41.2110
)
[1] => Array
(
[GroupCode] => 112
[GroupDesc] => Animal Production
[201308] => 0
[201309] => 3.1800
[201310] => 0
)
[2] => Array
(
[GroupCode] => 115
[GroupDesc] => Agriculture, Forestry Support
[201308] => 234.0400
[201309] => 0
[201310] => 343.0200
)
)
Loop through the $groupExport
array and on each iteration, loop through the sub-array and check if the each one of the period index exists. If they don't, initialize them with 0.
foreach ($groupExport as & $export) {
foreach ($periods as $period) {
if (!isset($export[$period])) {
$export[$period] = 0;
}
}
}
Note the &
before $export
. It means we're passing the array by reference — it's modifying $groupExport
on each iteration.
Note: This will mutate the original array. If you want to produce a new array, @AmalMurali's solution is superior.
Here's an alternate solution that uses some of PHP's built-in functions:
$keys = array_fill_keys($periods, 0);
array_walk($groupExport, function (&$item, $key, $keys) {
$item += $keys;
}, $keys);
Here's a demonstration at IDEOne.com.
$keys = array_fill_keys($periods, 0);
This converts your array of periods into a new array where the value from the original array is now the key, and the value is 0
.
array_walk($groupExport, function (&$item, $key, $keys) {
$item += $keys;
}, $keys);
We walk over each element of the array $groupExport
, and apply a function to each member. We pass each array element as a reference to our user defined function, which allows us to manipulate it directly.
Finally, we add $keys
to $item
which essentially merges the two arrays while maintaining key associations.
Array
(
[0] => Array
(
[GroupCode] => 111
[GroupDesc] => Crop Production
[201308] => 1.55
[201309] => 240.42
[201310] => 41.211
)
[1] => Array
(
[GroupCode] => 112
[GroupDesc] => Animal Production
[201309] => 3.18
[201308] => 0
[201310] => 0
)
[2] => Array
(
[GroupCode] => 115
[GroupDesc] => Agriculture, Forestry Support
[201308] => 234.04
[201310] => 343.02
[201309] => 0
)
)