我有一个包含50个索引值的数组。我在print_r($result);
之后得到的数组的一部分是
Array
(
[0] => Array
(
[ClassScheduleID] =>
[Location] => Array
(
[Latitude] =>
)
[ClassDescription] =>
(
[ImageURL] =>
[Level] =>
(
[Name] =>
)
[Program] =>
(
[Name] =>
)
)
[Staff] => Array
(
[FirstName] =>
)
)
[1] => Array
(
[ClassScheduleID] =>
[Location] => Array
(
[Latitude] =>
)
[ClassDescription] =>
(
[ImageURL] =>
[Program] =>
(
[Name] =>
)
)
[Staff] => Array
(
[FirstName] =>
)
)
[2] => Array
(
[ClassScheduleID] =>
[Location] => Array
(
[Latitude] =>
)
[ClassDescription] =>
(
[ImageURL] =>
[Program] =>
(
[Name] =>
)
)
[Staff] => Array
(
[FirstName] =>
)
)
)
我通过以下代码(代码的一部分)从数组中获取数据
if (!empty($result))
{
foreach ($result as $res)
{
$classscheduleid = $res['ClassScheduleID'];
if(isset($res['Location']))
{
$l_latitude = $res['Location']['Latitude'];
}
if(isset($res['ClassDescription']))
{
$c_img = $res['ClassDescription']['ImageURL'];
}
if(isset($res['ClassDescription']['Level']))
{
$c_l_name = $res['ClassDescription']['Level']['Name'];
}
if(isset($res['ClassDescription']['Program']))
{
$c_p_name = $res['ClassDescription']['Program']['Name'];
}
if(isset($res['Staff']))
{
$s_firstname = $res['Staff']['FirstName'];
}
$sql = "INSERT INTO class_detail (classscheduleid,l_latitude,c_img,c_l_name,c_p_name,s_firstname) VALUES ('".$classscheduleid."','".$l_latitude."',,'".$c_img."','".$c_l_name."','".$c_p_name."','".$s_firstname."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
}
我面临的问题是,当我试着在数据库中插入值时,它没有插入前8个索引值,它开始从[9]位置保存值。我正确地获取所有数据,因为我通过echo检查了所有变量。任何人都可以告诉我如何在数据库中正确保存数组的值
答案 0 :(得分:1)
$ l_latitude = $ res之后[&#39;位置&#39;] [&#39;纬度&#39;];使用普通的插入查询将其插入数据库,在$ c_img = $ res [&#39; ClassDescription&#39;] [&#39; ImageURL&#39;]之后写入更新查询后,从此处获取最后插入的ID;并检查你之前得到的最后插入的id。与其余部分类似地做到这一点。这是一个有点冗长的方法,但肯定会给你正确的值,并且很容易编码
答案 1 :(得分:0)
您可以尝试使用array_keys()获取数组中值的数组键和array_values(),然后使用逗号()将逗号插入到数据库中。
答案 2 :(得分:0)
更改
foreach ($result as $res)
要
foreach ($result as $key=>$res)