gpt4 book ai didi

php - 访问和打印嵌套数组

转载 作者:行者123 更新时间:2023-11-30 22:19:27 25 4
gpt4 key购买 nike

我有以下嵌套数组。

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
)
)
)
)

我想处理上面的数组并使用 foreach 循环构建一个插入查询,如下所示:

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');

我怎样才能做到这一点。预先感谢您的帮助。

最佳答案

您需要循环数组的每个部分。只需使用 foreach 3 次。将查询存储在数组中。让你的数组是 $arr

你的数组:

$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'
)
)
)
);

机制/技术:

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);

结果

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');

)

关于php - 访问和打印嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37085470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com