我正在尝试按PublishedAt排序。 sql是从json数据插入的,我需要获取最新的,但是此代码获取的最旧。
我的代码有什么问题?
$loop = mysqli_query($conn, "SELECT channelid, videoId FROM users ORDER BY id")
or die (mysqli_error($conn));
while ($row = mysqli_fetch_array($loop))
{
$channelid = $row['channelid'];
$url = 'https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId='.$channelid .'&maxResults=5&key=KEY';
$content = file_get_contents($url);
$json = json_decode($content, true);
if(!isset($json['items'])) continue; //skip if no items
$videos = ['videoId'=>'','videoId1'=>'','videoId2'=>'','videoId3'=>'','videoId4'=>''];
$i = 0;
foreach($json['items'] as $items)
{
$publishedAt = $items['snippet']['publishedAt'];
$key = 0==$i ? 'videoId' : 'videoId'.$i;
$videos[$key] = $items['id']['videoId'];
++$i;
}
$ii = 0;
$sql = "INSERT INTO users(channelid, publishedAt, videoId, videoId1, videoId2, videoId3, videoId4) VALUES('$channelid', '$publishedAt', '{$videos['videoId']}', '{$videos['videoId1']}', '{$videos['videoId2']}', '{$videos['videoId3']}', '{$videos['videoId4']}')
ON DUPLICATE KEY UPDATE channelid=VALUES(channelid), publishedAt=VALUES(publishedAt), videoId=VALUES(videoId), videoId1=VALUES(videoId1), videoId2=VALUES(videoId2), videoId3=VALUES(videoId3), videoId4=VALUES(videoId4);
";
mysqli_query($conn, "SET NAMES utf8");
if(!mysqli_query($conn,$sql))
{
die('Error : ' . mysqli_error($conn));
}
}
答案 0 :(得分:0)
当您遍历$json['items']
时,您将用每个循环的最后一项覆盖$publishedAt
。
如果只希望第一项的publishedAt,则应直接获取第一项(无需循环)。 但是,如果要插入所有项目,则应将查询放入foreach中。