Reputation: 1630
I have 3 simple arrays with same number of items
$id= array(1, 2, 3, 4, 5);
$fruit= array('apple', 'banana', 'ananas', 'orange', 'lemon');
$price= array(32, 54, 26, 97, 47);
I have two MySql tables. First table 'fruits' which contain rows 'id' and 'name' and second table 'prices' which contain rows 'fruit' and 'price'.
In table 'fruits' I need to insert items from arrays $id and $fruit. Items from $id should go into row 'id' and items from $fruit should god into row 'name' IF there is not a row with same id number. Also I need to insert all items from arrays $id an $price into table 'prices'. Same like in a previous table, items from array $id should be placed into row 'fruit' and items from array $price should be placed into row 'price'.
Thank you for helping.
Upvotes: 0
Views: 263
Reputation: 10467
$id= array(1, 2, 3, 4, 5);
$fruit= array('apple', 'banana', 'ananas', 'orange', 'lemon');
$price= array(32, 54, 26, 97, 47);
foreach($fruit as $key => $fruitName)
{
$query = '
INSERT INTO fruits (id, name)
VALUES ('.$id[$key].', '.$fruit[$key].')
';
// execute
$query = '
INSERT INTO prices (id, price)
VALUES ('.$id[$key].', '.$price[$key].')
';
// execute
}
But please don't ask me to validate input [existence of keys, etc] here - this is quick snippet that probably will help. ;]
BTW. It would be much better if you'd have one table fruits(id, name, price). ;]
Upvotes: 6
Reputation: 28174
Use array_combine()
to create two new arrays:
$id
with $fruit
$id
with $price
Loop through each of these two associative arrays, and insert your records.
Upvotes: 1