Implode 2 separate arrays?
I have a script with a query that gathers information from a db from two separate tables using a join. Now I want to inse开发者_StackOverflowrt those 2 arrays and their values side by side inside a new table.
$query = "INSERT INTO `new_table`
(column_a, column_b)
VALUES
(implode(something,$array_a), implode(something,$array_b))"
Obviously the syntax isn't right, but I was wondering if it was possible or if I'm on the wrong track. I tried a few queries and couldn't get them to line up for an insert - it exploded them one at a time.
The answer to this one is, as you would expect, dependent on exactly what you are trying to achieve.
I will assume that your two arrays are as follows (for the purposes of demonstration):
$arrayA = array(
'Alpha' ,
'Bravo' ,
'Charlie'
);
$arrayB = array(
'Zulu' ,
'Yankee' ,
'Xray'
);
Now, if you are wanting to place these values into a table (called the_table for ease of reference), so that they create a single row like so
column_a | column_b
"Alpha,Bravo,Charlie" | "Zulu,Yankee,Xray"
Then the SQL you would want to produce is
INSERT INTO `the_table` ( `column_a` , `column_b` )
VALUES ( "Alpha,Bravo,Charlie" , "Zulu,Yankee,Xray" )
And the PHP to produce that SQL could be
$sqlTpl = 'INSERT INTO `the_table` ( `column_a` , `column_b` )
VALUES ( "%s" , "%s" )';
$sqlStr = sprintf( $sqlTpl ,
implode( ',' , $arrayA ) ,
implode( ',' , $arrayB ) );
Now, if you were, instead, wanting to produce a set of matching rows, with one pair from each of the two arrays, like so
column_a | column_b
"Alpha" | "Zulu"
"Bravo" | "Yankee"
"Charlie" | "Xray"
The SQL would be
INSERT INTO `the_table` ( `column_a` , `column_b` )
VALUES ( "Alpha" , "Zulu" ) ,
( "Bravo" , "Yankee" ) ,
( "Charlie" , "Xray" )
And the PHP to produce that could be
$sqlTpl = 'INSERT INTO `the_table` ( `column_a` , `column_b` )
VALUES ( %s )';
$sqlArr = array();
foreach( $arrayA as $k => $v )
$sqlArr[] = '"'.$arrayA[$k].'" , "'.$arrayB[$k].'"';
$sqlStr = sprintf( $sqlTpl ,
implode( ' ) , ( ' , $sqlArr ) );
Use:
$query = sprintf("INSERT INTO `new_table`
(column_a, column_b)
VALUES
('%s', '%s')",
implode(something, $array_a),
implode(something, $array_b));
That said, typically not a great idea to be storing denormalized data.
精彩评论