开发者

How to merge my arrays for DB insertion?

I have 2 associative arrays.

开发者_如何学CArray ( [title1] => test1 [title2] => test2 [title3] => test3 )

and

 Array ( [image1] => images1.jpeg [image2] => images2.jpg [image3] => images3.png ) 

I want to insert each title and image name into database columns(image title and image name).

How it is possible? Anyway to merge them and after that do insertion?


$finalArray = array();
// Use min to avoid improper "OutOfBounds"
$lengthOfArray = min(count($array1), count($array2));

for(i = 1; i <= $lengthOfArray; $i++) {
   array_push($finalArray,
       array(
         'title' => $array1['title' + $i],
         'image' => $array2['image' + $i]
       )
   );
}

With this, in your finalArray you will have tuples of title an image for every database entry.


Look at array_combine()


Maybe instead of combining the arrays, you can use a foreach to construct your query from the two arrays:

//ARRAYS
$a1=array('title1' => 'test1','title2' => 'test2','title3' => 'test3',);
$a2=array('image1' => 'images1.jpeg', 'image2' => 'images2.jpg', 'image3' => 'images3.png');

$fos=''; //we will collect values into this string
foreach ($a1 as $k=>$v) { //we iterate through the first array
    $k2=substr($k, 5);  //we get the number from the array key (like 2 from title2)
    $fos.=empty($fos) ? '' : ', '; //adding commas when needed
    $fos.="('{$v}', '{$a2['image'.$k2]}')"; //adding the right values to the values string
}

$q="insert into images (title, filename) values $fos"; //and finishing up the query

In this case the constructed query will be like:

insert into images (title, filename) values 
('test1', 'images1.jpeg'), 
('test2', 'images2.jpg'), 
('test3', 'images3.png')

Note: of course array values need to be correctly escaped for DB usage


array_merge($array1, $array2);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜