Php Sql Array in to Array

44 views Asked by At

If we have 3 arrays for example:

Array= a, b, c. 
Array2= 1, 2, 3  
Array3= 0, 4, 5  

I want to insert them in to my sql table like this

A 1 0
A 2 4
A 3 5
B 1 0
B 2 4
B 3 5
C 1 0
C 2 4
C 3 5

All second and third array values will be stored with each and every value of first array.

How can i do that? Using php and sql

1

There are 1 answers

2
Jared On

Itterate first array by value, inside this loop itterate second array by index, take values from second and third array by this index:


<?php

$dbh = new PDO('mysql:host=localhost;dbname=test', 'db_username', 'secret_password');

$array1 = ['a','b','c'];
$array2 = [1,2,3];
$array3 = [0,4,5];

$sth = $dbh->prepare("INSERT INTO your_table set string_column = ?, integer_column1 = ?, integer_column2 = ?");

foreach( $array1 as $string_value )
    foreach( array_keys($array2) as $integer_index )
        $sth->execute( $string_value, $array2[ $integer_index ], $array3[ $integer_index ] );