I got the following array:
array(4) {
[0] => array(2) {
[1] => string(1)
"2" ["month"] => string(2)
"01"
}[1] => array(2) {
[1] => string(2)
"74" ["month"] => string(2)
"02"
}[2] => array(2) {
[1] => string(3)
"233" ["month"] => string(2)
"03"
}[3] => array(2) {
[1] => string(2)
"21" ["month"] => string(2)
"05"
}
}
As you can see the value for April is missing. I parse it as follows:
$delivbymonth = $query->getResult();//A DQL Query which returns the above array
$MyArray = array();
for($i=0;$i<=11;++$i)
{
if(isset($delivbymonth[$i]['month']) && $delivbymonth[$i]['month']==$i+1)
{
$MyArray[$i] = $delivbymonth[$i][1];
}else{$MyArray[$i]=0;}
}
So I want a final array of 12 numbers (NOT a key=>value pairs). If there is no number (like for April here) I want the number in array set to zero. Everything works fine untill the for loop get to the omitted month. It sets the value for the 4th number in array to zero as it is supposed to, but after that ALL remaining elements in array are set to zero not regarding the fact that the value for May actually exists. The data for first 3 month is parsed correctly, i.e. the element in my final array are NOT zero (2, 74, 233). Does anybody know the reason for that? Thank You
$myArray = array_fill(0, 12, 0);
foreach ($delivbymonth as $deliv) {
$myArray[intval($deliv['month'] - 1)] = $deliv[1];
}
var_dump($myArray);
OUTPUT:
array(12) {
[0] =>
string(1) "2"
[1] =>
string(2) "74"
[2] =>
string(3) "233"
[3] =>
int(0)
[4] =>
string(2) "21"
[5] =>
int(0)
[6] =>
int(0)
[7] =>
int(0)
[8] =>
int(0)
[9] =>
int(0)
[10] =>
int(0)
[11] =>
int(0)
}
Explanation:
The condition below in your original code was being met by the first 3 elements.
if(isset($delivbymonth[$i]['month']) && $delivbymonth[$i]['month']==$i+1)
However on the fourth element (when $i = 3) the part of the condition
$delivbymonth[$i]['month']==$i+1
evaluates to false (5 == 4), then from this point on every loop will end up on the else clause, causing all subsequent elements to be 0.