How to create an associative multidimensional array from an input form

I need to create a multidimensional array from an input form because I would like to pass information to mysql. I created it, but how can I make it associative? My input:

echo "<input type='number' name='hours_to_save[$my_date][$project[$i]]'/>"

      

Here's how to do it now:

array(30) {
    ["2017-05-01"]=>
        array(3) {
            ["kompan"]    => string(1) "2"
            ["5 ogrodow"] => string(1) "3"
            ["karolowo"]  => string(1) "4"
    },
    ...
}

      

But I would like like this:

array(30) {
  ["2017-05-01"]=>
        array(3) {
            ["project"] => "kompan" , ["hours"] => string(1) "2"

            ["project"] =>"5 ogrodow" , ["hours"] => string(1) "3"

            ["project"] => "karolowo" , ["hours"] => string(1) "4"
    },
    ...
}

      

+3


source to share


2 answers


Input:

$input=array(
    "2017-05-01"=>["kompan"=>"2","5 ogrodow"=>"3","karolowo"=>"4"],
    "2017-05-02"=>["kompan"=>"5","5 ogrodow"=>"6","karolowo"=>"7"]    
);

      

Method # 1 ( foreach () x2 * recommended)

foreach($input as $d=>$a){
    foreach($a as $k=>$v){
        $result[$d][]=['project'=>$k,'hours'=>$v];
    }
}
var_export($result);

      

It means:



$result                         // declare output array
       [$d]                     // use the date values as keys
           []=                  // autoincrement the keys in the subarray
              ['project'=>$k,   // each subarray 1st element will use 'project' as the key and the input subarray key as its value
               'hours'=>$v];    // each subarray 2nd element will use 'hours' as the key and the input subarray value as its value

      

Method # 2 ( foreach()

and array_map () - array_keys () * for demonstration)

foreach($input as $k=>$a){
    $result[$k]=array_map(function($a,$b){return ['project'=>$a,'hours'=>$b];},array_keys($input[$k]),$input[$k]);
}
var_export($result);

      

Output (regardless of method):

array (
  '2017-05-01' => 
  array (
    0 => 
    array (
      'project' => 'kompan',
      'hours' => '2',
    ),
    1 => 
    array (
      'project' => '5 ogrodow',
      'hours' => '3',
    ),
    2 => 
    array (
      'project' => 'karolowo',
      'hours' => '4',
    ),
  ),
  '2017-05-02' => 
  array (
    0 => 
    array (
      'project' => 'kompan',
      'hours' => '5',
    ),
    1 => 
    array (
      'project' => '5 ogrodow',
      'hours' => '6',
    ),
    2 => 
    array (
      'project' => 'karolowo',
      'hours' => '7',
    ),
  ),
)

      

+1


source


You can use foreach loop to insert into mysql. Foreach will continue to work with arrays.



$newArr = [];
$i=0;
foreach ($yourArray as $key=>$val) {
   $newArr['date'] = $key;
   foreach ($val as $dKey=>$row) {
      $newArr['date'][$i]['project'] = $dKey;
      $newArr['date'][$i]['hours'] = $row;
      $i++;
   }
}

      

0


source







All Articles