我正在从json解码的响应中插入一些值到我的数据库,但是某些值不仅以某种方式插入到它们自己的行中,而且还插入到具有其中一些值的其他行中。因此,例如,如果一行有自己的音频,它会保留其音频,但它也可以获得其他行的视频/照片/涂鸦。但是,那些没有附件的帖子会将这些字段保留为空。这是一种非常奇怪的行为,我已经迷失在这些循环中。
foreach ( $response->posts as $key => $element ) {
$comment_id = $element->id;
$user_id = $element->from_id;
$usersget = $var_hidden_from_this_example;
$user_name = $var_hidden_from_this_example_2;
$user_photo = $var_hidden_from_this_example_3;
$comment_text = $response->posts[$key]->text;
$comment_date = date('Y-m-d H:i:s', $response->posts[$key]->date);
if ( !isset ($element->attachments) ) {
$photo = $graffiti = $video = $audio = null;
}
else {
foreach ( $element->attachments as $key_att => $attachment ) {
if ( $attachment->type == 'photo' ) {
if ( $attachment->photo->album_id == $example_only ) {
$graffitis = array();
$graffitis[] = $attachment->photo->$example_var;
}
else {
$photos = array();
$photos[] = $attachment->photo->$example_var;
}
}
if ( $attachment->type == 'video' ) {
$videos = array();
$videos[] = $example_var2;
}
if ( $attachment->type == 'audio' ) {
$audios = array();
$audios[] = $example_var3;
}
}
if ( isset ($photos) ) {
$photo = implode('\n', $photos);
}
if ( isset ($graffitis) ) {
$graffiti = implode('\n', $graffitis);
}
if ( isset ($videos) ) {
$video = implode('\n', $videos);
}
if ( isset ($audios) ) {
$audio = implode('\n', $audios);
}
}
$data = [
'comment_id' => $comment_id,
'user_id' => $user_id,
'user_name' => $user_name,
'user_photo' => $user_photo,
'url' => $referer,
'comment_text' => $comment_text,
'comment_date' => $comment_date,
'photo' => $photo,
'graffiti' => $graffiti,
'video' => $video,
'audio' => $audio,
];
$sql = "INSERT INTO level_1 (comment_id, user_id, user_name, user_photo, url, comment_text, comment_date, photo, graffiti, video, audio) VALUES (:comment_id, :user_id, :user_name, :user_photo, :url, :comment_text, :comment_date, :photo, :graffiti, :video, :audio)";
$pdo->prepare($sql)->execute($data);
}
换句话说,值photo
,graffiti
,video
和audio
不仅会插入到相应的行中,而且相同的值也会插入到没有自己的此类值的所有表行中(除了行'有任何这些 - 他们按预期保持空白。
正如评论中指出的那样,除非您看到该类型的附件,否则您不会重新初始化您的$graffitis
数组等。因此,对于没有视频的元素,它会从前一个包含视频的元素中获取视频。尝试重写你的循环,如下所示:
$graffitis = $photos = $videos = $audios = array();
foreach ( $element->attachments as $key_att => $attachment ) {
if ( $attachment->type == 'photo' ) {
if ( $attachment->photo->album_id == $example_only ) {
$graffitis[] = $attachment->photo->$example_var;
}
else {
$photos[] = $attachment->photo->$example_var;
}
}
if ( $attachment->type == 'video' ) {
$videos[] = $example_var2;
}
if ( $attachment->type == 'audio' ) {
$audios[] = $example_var3;
}
}