Search code examples
phparraysarray-push

Create an array with dynamic input in PHP


I have to create a array dynamically like I have a method which will pass keys and based on those keys I need to create arrays inside them Format will be like-

{
   "TEST1":{
         "140724":[
            {
               "A":"1107",
               "B":4444,
               "C":"1129",
               "D":"1129"
            },
            {
               "A":"1010",
               "B":2589,
               "C":"1040",
               "D":"1040"
            }
         ],
          "140725":[

         ]
      }
}

So how should I frame this logic inside for loop. I am new to php so formatting the same creating trouble.

$json_Created = array("TEST1" => array());
foreach($val as $key=>$value){
  array_push($json_created,array($key = array()));
}

The entire array is dynamic, so like I have 140724 ,,, till 140731 (actually date format yymmdd), any amount if numbers can be considered. SO that part is dynamic moreover some dates may be wont have any values and some will have.

So my main point is to develop that logic so that irrespective the number of inputs , my array formation must be intact.


Solution

  • Finally managed to write the code-

    $keys_content = array("starttime", "id", "duration", "endtime");
    $dates        = array();//140724,140725,140726140727
    $mainID       =“TEST1”;
    
    $arraySuperMain = array();
    $arrayMain      = array();
    
    for ($j = 0; $j < count($dates); $j++) {
    $array_main = array();
    
    $subset = array();
    
    for ($i = 0; $i < count($keys_content); $i++) {
    $key    = $keys_content[$i];
    $subset = array_push_assoc($subset, $key, "Value".$i);
    }
    $array_main = array_push_assoc($array_main, $dates[$j], $subset);
    array_push($arrayMain, $array_main);
    
    }
    $createdJSON = array_push_assoc($arraySuperMain, $mainID, $arrayMain);
    
    public static function array_push_assoc($array, $key, $value) {
        $array[$key] = $value;
        return $array;
    }