【问题标题】:storing json_decode data from oldest to newest in MySql database在 MySql 数据库中从最旧到最新存储 json_decode 数据
【发布时间】:2018-03-29 14:22:45
【问题描述】:

我有这个代码:

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

【问题讨论】:

    标签: php mysql json laravel jsondecoder


    【解决方案1】:

    这只是使用 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();
            }
    

    【讨论】:

      猜你喜欢
      • 2012-07-27
      • 1970-01-01
      • 2012-03-07
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多