Please help me with this array printing.
Array
[year_2014] => Array
(
[0] => Array
(
[amount] => 21960
[year] => 2014
[month] => 1
)
[1] => Array
(
[amount] => 25866
[year] => 2014
[month] => 2
)
[2] => Array
(
[amount] => 7840
[year] => 2014
[month] => 3
)
[3] => Array
(
[amount] => 424644
[year] => 2014
[month] => 5
)
[4] => Array
(
[amount] => 22052
[year] => 2014
[month] => 6
)
[5] => Array
(
[amount] => 28037
[year] => 2014
[month] => 7
)
)
I need to echo amount in according to month so the Output will be,
Result
21960, 25866, 7840, 0, 424644, 22052, 28037, 0, 0, 0, 0, 0
That is if a month is not present then the value need to be zero,I need all the twelve month.
My dear Good Hearts please help me to get this result.
Some background
project is done in codeigniter , I have messed with some for, foreach but it's not working.
Thank you.
Just try with:
$output = array_fill(0, 12, 0);
array_map(function ($item) use (&$output) {
$output[$item['month'] - 1] = $item['amount'];
}, $input['year_2014']);
or with simple
foreach
:$output = array_fill(0, 12, 0);
foreach ($input['year_2014'] as $item) {
$output[$item['month'] - 1] = $item['amount'];
}
Output:
array (size=12)
0 => int 21960
1 => int 25866
2 => int 7840
3 => int 0
4 => int 424644
5 => int 22052
6 => int 28037
7 => int 0
8 => int 0
9 => int 0
10 => int 0
11 => int 0
Explanation:
array_fill
creates an array with 12 elements filled with 0
values.foreach
loops over year_2014
data arrays and sets item's amounts to the month - 1
position.array_map
does the same as foreach
and can be an overkill here, but also works well.
0 comments:
Post a Comment