Search code examples
phpmysqljsonlaraveljsondecoder

storing json_decode data from oldest to newest in MySql database


I have this code:

$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();
        }

And what it does is grab content from JSON URL and store it in to a database which it's based on LaraveL. so the issue is it's storing the data from newest to oldest but what I want to is store the items from oldest to newest. That was the first question and the second question is how to make it store only the newest ones not duplicate those that are already stored and only check for those that are new only?


Solution

  • Here's how it's done just by using 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();
            }