Below is my result array
$resultVal = Array ( [0] => Array ( [0] => Array ( [crate] => 13.51 [ucount] => 36 [udate] => 2016-06-30 ) [1] => Array ( [crate] => 20.51 [ucount] => 36 [udate] => 2016-07-30 ) ) )
and below is my month array
$MonthArray =array("June 2016","July 2016","August 2016");
And my expected array is below,
$expectedArray = Array ( [0] => Array ( [crate] => 13.51 [ucount] => 36 [udate] => June 2016 ) [1] => Array ( [crate] => 0 [ucount] => 0 [udate] => July 2016 ) [2] => Array ( [crate] => 0 [ucount] => 0 [udate] => Aug 2016 ) )
I have to display expected array on basis of month array.
No value is present in month of July 2016, so I have to add full set of elemenst.
I am using array_combine()
and in_array()
to set count 0
if no date for particular month.
But for adding element is only set for one element not for both elements.
Please suggest a best solution.
Advertisement
Answer
you need to loop the month array like below .
<?php $resultVal = Array ("0" => Array("0" => Array("crate" => 13.51,"ucount" => 36,"udate" => '2016-06-30'))); $MonthArray =array("June 2016","July 2016"); $formated_column = array_map(function($v){ return date('F Y',strtotime($v['udate'])); },$resultVal[0]); //here using array_map to build a formated udate array column . $new_array =array(); for($i=0;$i<count($MonthArray);$i++){ //here looping month column $exists_array_key = array_search($MonthArray[$i],$formated_column); //here searching the month value exists in formated array or not . if($exists_array_key !==false){ $resultVal[0][$exists_array_key]['udate']=date('F Y',strtotime($resultVal[0][$exists_array_key]['udate'])); $new_array[]= $resultVal[0][$exists_array_key]; }else{ $new_array[]= Array("crate" =>"","ucount" =>"","udate" =>$MonthArray[$i] ); } } print_r($new_array ); ?>
OUT PUT :
Array ( [0] => Array ( [crate] => 13.51 [ucount] => 36 [udate] => June 2016 ) [1] => Array ( [crate] => [ucount] => [udate] => June 2016 ) )