我有这个代码:
$url = 'http://example.com/523223.json?';
$json= file_get_contents($url);
$data = json_decode($json);
$rows = $data->{'items'};
foreach ($rows as $row) {
echo '<p>';
$title = $row->name;
$description = $row->description;
$link = $row->link;
$image_link = $row->thumbnails;
$path = $image_link->large;
$filename = basename($path);
try {
Image::make($path)->save(public_path('storage/posts/' . $filename));
} catch (\Intervention\Image\Exception\NotReadableException $e) {
Image::make($path)->save(public_path('storage/posts/' . 'https://lh3.googleusercontent.com/yI8LPDBhjvqLR1mQMitJlibZdWqaYAlMVUJK6zpBQkOb_Bk03qn_l2SQyn5yY__KZcY-=w300-rw'));
}
$post = new Post;
$post->title = $title;
$post->body = '..';
$post->excerpt = $description;
$post->meta_description = $link;
$post->image = 'posts/' . $filename;
$post->save();
}
它的作用是从 JSON URL 中获取内容并将其存储到基于 LaraveL 的数据库中。所以问题是它存储从最新到最旧的数据,但我想要的是从最旧到最新存储项目。 这是第一个问题,第二个问题是如何使其仅存储最新的而不重复已存储的那些并且仅检查那些新的?
最佳答案
以下是仅使用 array_reverse 即可完成的操作:
$url = 'http://example.com/523223.json?';
$json= file_get_contents($url);
$data = json_decode($json);
$rows = $data->{'items'};
foreach (array_reverse($rows) as $row) {
echo '<p>';
$title = $row->name;
$description = $row->description;
$link = $row->link;
$image_link = $row->thumbnail;
$path = $image_link;
$filename = basename($path);
try {
Image::make($path)->save(public_path('storage/posts/' . $filename));
} catch (\Intervention\Image\Exception\NotReadableException $e) {
Image::make($path)->save(public_path('storage/posts/' . 'https://lh3.googleusercontent.com/yI8LPDBhjvqLR1mQMitJlibZdWqaYAlMVUJK6zpBQkOb_Bk03qn_l2SQyn5yY__KZcY-=w300-rw'));
}
$post = new Post;
$post->title = $title;
$post->body = '..';
$post->excerpt = $description;
$post->meta_description = $link;
$post->slug = $link;
$post->image = 'posts/' . $filename;
$post->save();
}
关于php - 将 json_decode 数据从最旧到最新存储在 MySql 数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49558565/