PHP Perform foreach on array key value -
PHP Perform foreach on array key value -
i have array (below) need perform multiple mysql inserts from.
the key value needs inserted, , value number of times needs inserted.
for example, on first iteration, hope insert "1" twelve times. in sec iteration, hope insert "2" twenty-eight times.
array ( [1] => 12 [2] => 28 [3] => 21 [4] => 9 [5] => 0 )
now, i'm aware it's best utilize 1 query insert multiple rows, rather individual insert queries, hope code below reflects this.
my question is: how can iterate through key value, instead of individual keys (although need iterate through keys well)?
$insert = array(); foreach ($ret $key => $item) // $ret array above { $insert[] = "('". mysql_real_escape_string($item) . "'," . $key . "')"; // insert query should repeat many times each array value } echo "insert table (id, key) values " . implode(',', $insert);
you need run sec loop within foreach
foreach ($ret $key => $item) { for($i=1; $i<=$item; $i++) { $insert[] = "('". mysql_real_escape_string($item) . "'," . $key . "')"; } }
and create sure id not primary unique in table.
php
Comments
Post a Comment