Iamnewbie Iamnewbie - 2 months ago 10
MySQL Question

PHP store array to database logical issue

I have an array as follows:

$data = array('John',22,'Peter',31,'Kevin',30,'Jessy',28.......'Revin',23);


This array will contains thousands of elements in the same format like name, age.

Now I need to insert this array in a table as follows by using PHP/MYSQL function.

--------------------
Id Name Age
--------------------
1 John 22
2 Peter 31
3 Kevin 30


Please note don't give options like loops or explode. Help is appreciated

Answer

I hope the bellow code will work based on your requirement, HAPPY CODING :-)

        $data=array('John',22,'Peter',31,'Kevin',30,'Jessy',28);// list of array
        $array=array_chunk($data, 2);// converting array to  multidimensional array
        $arraytostr = implode(',', array_map(function($el){ return "('".$el['0']."',".$el['1'].")"; }, $array)); // implode the multidimensional array to ','separate array
        $query="INSERT INTO test (fname,age) VALUES ".$arraytostr;// append the new ',' separate array with query
Comments