I have the following nested array.
Array
(
[animals] => Array
(
[carnivores] => Array
(
[tiger] => Array
(
[eyes] => 2
[legs] => 4
)
[lion] => Array
(
[eyes] => 2
[legs] => 4
)
)
[herbivores] => Array
(
[deer] => Array
(
[eyes] => 2
[legs] => 4
)
[elephant] => Array
(
[eyes] => 2
[legs] => 4
)
)
)
)
I want to process the above array and build an insert query using foreach loop as follows:
INSERT INTO `abc` (column1,column2,column3,column4, column5)
VALUES ('animals','carnivores','tiger','2','4');
.
.
.
.
INSERT INTO `abc` (column1,column2,column3,column4, column5)
VALUES ('animals','herbivores','elephant','2','4');
How can I achieve this. Thanks in advance for the help.
You need to loop every part of your array. Just use foreach
3 time. store the query in an array. Let your array is $arr
.
Your array:
$arr = array(
"animals" => array
(
"carnivores" => array
(
"tiger" => array
(
"eyes" => '2',
"legs" => '4'
),
"lion" => Array
(
"eyes" => '2',
"legs" => '4'
)
),
"herbivores" => array
(
"deer" => array
(
"eyes" => '2',
"legs" => '4'
),
"elephant" => array
(
"eyes" => '2',
"legs" => '4'
)
)
)
);
Mechanism / Technique:
foreach($arr as $key => $value){
$str = "INSERT INTO `abc` (column1,column2,column3,column4, column5) VALUES(";
$qryArr = array();
foreach($value as $key2 => $value2){
foreach($value2 as $key3 => $value3){
$eyes = $value3['eyes'];
$legs = $value3['legs'];
$qryArr[] = $str."'$key', '$key2', '$key3', '$eyes', '$legs');";
}
}
}
print_r($qryArr);
Result
Array
(
[0] => INSERT INTO `abc` (column1,column2,column3,column4, column5) VALUES('animals', 'carnivores', 'tiger', '2', '4');
[1] => INSERT INTO `abc` (column1,column2,column3,column4, column5) VALUES('animals', 'carnivores', 'lion', '2', '4');
[2] => INSERT INTO `abc` (column1,column2,column3,column4, column5) VALUES('animals', 'herbivores', 'deer', '2', '4');
[3] => INSERT INTO `abc` (column1,column2,column3,column4, column5) VALUES('animals', 'herbivores', 'elephant', '2', '4');
)
Use PDO for inserting and foreach to loop through all the values in multi array.
$sql = 'INSERT INTO `abc` (...) VALUES (?,?,?,?,?)';
$stmt = $conn->prepare($sql);
$data = [];
foreach ($animals as $key_animals => $animalGroup) {
foreach ($animalGroup as $key_animalGroup => $animal) {
foreach ($animal as $key_animal => $animalProps) {
$data = [$key_animals, $key_animalGroup, $key_animal, $animalProps['eyes'], $animalProps['legs']];
$stmt->execute($data);
}}}
Have not tested this but something along these lines.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.