在MySql数据库中存储从最旧到最新的json_decode数据

时间:2018-03-29 14:22:46

标签: php mysql json laravel jsondecoder

我有这段代码:

$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的数据库中。所以问题是它存储的数据从最新到最旧,但我想要的是存储从最旧到最新的项目。 这是第一个问题,第二个问题是如何使它只存储最新的那些不重复已经存储的那些并仅检查那些只是新的?

1 个答案:

答案 0 :(得分:0)

以下是使用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();
        }