PHP assigning only specific values into an incremental variable during a loop -


i have array:

array (     [users] => array         (             [0] => array                 (                     [column] => email                     [value] => fskdjhfkjf@mai.com                 )              [1] => array                 (                     [column] => nickname                     [value] => dpucci                 )          )      [social] => array         (             [0] => array                 (                     [column] => user_id                     [value] => opweirpor                 )          )  ) 

starting array i'll have build string this:

insert(users, array(email=>fskdjhfkjf@mai.com,nickname=>dpucci) 

and this:

insert(social, array(user_id=>opweirpor) 

this doing:

foreach ($tables $table => $queries) {     foreach ($queries $query) {         $insert .= $query['column'] . '=>' . $query['value'] . ',';     }     echo 'insert(' . $table . ', array(' . $insert . ')'; } 

the problem result getting following:

insert(users, array(email=>fskdjhfkjf@mai.com,nickname=>dpucci) 

and:

insert(social, array(email=>fskdjhfkjf@mai.com, nickname=>dpucci, user_id=>opweirpor) 

this because variable $insert incremented each new loop , adding results instead ones need each $tables loop.

how can achieve expected result?

because keep appending string same $insert in inner loop, ran many times. clear insert variable after have finished it, i.e. after inner loop. (untested)

foreach ($tables $table => $queries) {     foreach ($queries $query) {         $insert .= $query['column'] . '=>' . $query['value'] . ',';     }     echo 'insert(' . $table . ', array(' . $insert . ')';      // add line     $insert = "";  } 

or, put before inner foreach loop, has advantage ensure $insert not polluted previous codes or otherwise uninitialized giving php warnings.

foreach ($tables $table => $queries) {      // add line     $insert = "";      foreach ($queries $query) {         $insert .= $query['column'] . '=>' . $query['value'] . ',';     }      echo 'insert(' . $table . ', array(' . $insert . ')';  } 

however, code creates

insert(users, array(email=>fskdjhfkjf@mai.com,nickname=>dpucci,) 

note comma after dupcci. don't think want. fix this, remove trailing comma substr:

foreach ($tables $table => $queries) {      // add line     $insert = "";      foreach ($queries $query) {         $insert .= $query['column'] . '=>' . $query['value'] . ',';     }      // add 1 more line here     $insert = substr($insert, 0, -1);      echo 'insert(' . $table . ', array(' . $insert . ')';  } 

also, check desired output. seems brackets not balanced , strings unquoted. sure want?


Comments