2

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

3
  • Why can't/won't you use looping? That's the only sensible way to do this. Commented May 19, 2014 at 6:57
  • you definitely need for or foreach or while loop to do this. There is no way to operate with array with unknown way without a loop. Commented May 19, 2014 at 7:01
  • IF we use forloop consider that 1L records.. then browser will say "Cant process and Force to Quit". There is a way apart from LOOP that only I am trying.. Commented May 20, 2014 at 4:40

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

3
$query = $pdo_db->prepare("
INSERT
INTO table (
    name,
    age
)
VALUES " . rtrim(str_repeat('(?,?),', count($data)/2), ',')
);
$query->execute($data);

2 Comments

If the array is big enough and the server is MySQL the end result could be a Server has gone away error. It is a pretty cunning solution otherwise.
It's plain and simple not using any looping, just as the OP requested. The input array is a plain hash converted to a list so it can simply be counted and then divided by 2. The rest is string magic. As to the size of the array, well...suppose the OP could splice the array and repeat this method over and over again IF there's more than MySQL can handle in a single query.
0

No way to do this without loops, imo.

$data = array('John',22,'Peter',31,'Kevin',30,'Jessy',28);
$length = count($data);

for($i=0;$i<$length;$i+=2) {
    $sql = 'INSERT INTO <TABLE> (`Name`,`Age`) VALUES ("' . ( $data[$i] ) . ',"' . $data[$i+1] . '");';
}

The array can be arranged in a better way to represent the data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.