Search code examples
phpmysqlmultidimensional-arrayassociative-arrayform-processing

difficulty adding a key => value pair to a multidimensional associative array using a foreach loop in php


I'm using a multidimensional associative array to store user input to insert in a mysql UPDATE statement later.

$updateFields = array();
foreach($fields as $column => $field){
    if (isset($_POST[$field]) && !empty($_POST[$field])){
        if($column == "a" || $column == "b" || $column == "c" || $column == "d" || $column == "e" || $column == "f" || $column == "g" ){
            $updateFields[0] = [$column => "$_POST[$field]"];
        }
        else if($column == "h" || $column == "i"){
            $updateFields[1] = [$column => "$_POST[$field]"];
        }
        else if($column == "j" || $column == "k" || $column == "l" || $column == "m"){
            $updateFields[2] = [$column => "$_POST[$field]"];
        }
    }
}

The layout above that I'm using creates the array, but stores only the last key:value pairs of the 'child' associative array within the 'parent' associative array.

Visualization using print_r:

Array (
       [0] => Array (
              [g] => value
              ) 
       [1] => Array (
              [i] => value 
              ) 
       [2] => Array ( 
              [m] => value 
              ) 
       )

What I'm trying to accomplish:

Array ( 
       [0] => Array (
              [a] => value 
              [b] => value 
              [c] => value 
              [d] => value 
              [e] => value 
              [f] => value 
              [g] => value 
              ) 
       [1] => Array ( 
              [h] => value 
              [i] => value 
              ) 
       [2] => Array ( 
              [j] => value 
              [k] => value 
              [l] => value 
              [m] => value 
              ) 
       )

I've seen multiple threads on stackoverflow concerning inserting a key:pair value in an associative array, so I hope this doesn't qualify as a duplicate. I'd be happy to provide more information if anybody is interested.


Solution

  • try this...

    $updateFields = array();
    foreach($fields as $column => $field){
        if (isset($_POST[$field]) && !empty($_POST[$field])){
            if($column == "a" || $column == "b" || $column == "c" || $column == "d" || $column == "e" || $column == "f" || $column == "g" ){
                $updateFields[0][$column] = $_POST[$field];
            }
            else if($column == "h" || $column == "i"){
                $updateFields[1][$column] = $_POST[$field];
            }
            else if($column == "j" || $column == "k" || $column == "l" || $column == "m"){
                $updateFields[2][$column] = $_POST[$field];
            }
        }
    }