简体   繁体   中英

Saving data from a nested JSON decoded array into a Laravel DB

I have an array that outputs like this

array:25 [▼
      1 => array:3 [▼
        "title" => "The Superfish problem is Microsoft's opportunity to fix a huge problem and have manufacturers ship their computers with a vanilla version of Windows. Versions of windows preloaded with crapware (and now malware) shouldn't even be a thing."
        "created" => 1424600986
        "comments" => array:6 [▼
          0 => "<!-- SC_OFF --><div class="md"><p>Lenovo did a stupid/terrible thing by loading their computers with malware. But HP and Dell have been loading their computers with unnecessary software for years now.</p>"
          1 => ""
          2 => "<p>The people that aren't smart enough to uninstall that software, are also not smart enough to blame Lenovo or HP instead of Microsoft (and honestly, Microsoft deserves some of the blame for allowing these OEM installs anways).</p>"
          3 => ""
          4 => "<p>There are many other complications that result from all these differentiated versions of Windows. The time is ripe for Microsoft to stop letting companies ruin windows before the consumer even turns the computer on.</p>"
          5 => "</div><!-- SC_ON -->"
        ]
      ]
      2 => array:3 [▶]
      3 => array:3 [▶]

What I want to do is to get to the comments array and the for each comment inside the nested array I want to extract each one and save it into the DB

I have tried to do it like this

$counter = 1; 
foreach ($posts as $post) {
    //foreach post get the data and store it in a database
    $allData[$counter]['title']= $post['data']['title'];

    //Foreach Title, get a sentiment using the sentiment analysis
    $sentiment = SentimentAnalysis::decision($allData[$counter]['title']);

    $allData[$counter]['created']= $post['data']['created'];

    RedditPosts::create([
            'title' => $allData[$counter]['title'], 
            'created' => date($allData[$counter]['created']),
            'sentiment' => $sentiment,
            'search_identifier' => $search_id,
            'search_phrase' => $searchPhrase
            ]);

    foreach($posts['comments'] as $comment) {
        $sentiment = SentimentAnalysis::decision($allData[$counter]['comments']);
              $comment = RedditComment::create([
                'comment' => $comment,
                'sentiment' => $sentiment,
                'search_identifier' => $search_id,
                'search_phrase' => $searchPhrase
                ]);
           }

    $counter ++;
}   

However this does not work. I get undefined index on comments. I believe that I am on the right track, I just need to find a way to access this array of comments within the array of posts.

Is there a way to loop through this array and grab every comment strip the html and then save it into the DB

***************************SOLVED*************************************

This was solved like this

//Collect the data to be stored in the DB
    $allData=[];

    $counter = 1; 


    foreach ($posts as $post) {
        //foreach post get the data and store it in a database
        $allData[$counter]['title']= $post['data']['title'];

        //Foreach Title, get a sentiment using the sentiment analysis
        $sentiment = SentimentAnalysis::decision($allData[$counter]['title']);

        $allData[$counter]['created']= $post['data']['created'];

        //store this in the DB to have access to the information at a later stage
        RedditPosts::create([
                'title' => $allData[$counter]['title'], 
                'created' => date($allData[$counter]['created']),
                'sentiment' => $sentiment,
                'search_identifier' => $search_id,
                'search_phrase' => $searchPhrase
                ]);

        $allData[$counter]['comments'] = explode(PHP_EOL, $post['data']['selftext_html']);

        foreach($allData[$counter]['comments'] as $comment) {

            $sentiment = SentimentAnalysis::decision($comment);

                  //store this in the DB to have access to the information at a later stage
                  RedditComments::create([
                    'comment' => strip_tags(html_entity_decode($comment)),
                    'created' => date($allData[$counter]['created']),
                    'sentiment' => $sentiment,
                    'search_identifier' => $search_id,
                    'search_phrase' => $searchPhrase
                    ]);
               }

        $counter ++;
    }   
$threads = $SearchResultsArray['data']['children'];

foreach($threads as $thread) {
   $parent = RedditThread::create(['title' => $thread['title']);
   foreach($threads['comments'] as $comment) {
      $comment = RedditComment::create(['comment' => $comment]);
      $parent->comments()->save($comment);
   }
}

You need to separate the idea of a thread parent from a child. You don't have to use the model names I've used here but this is the basic idea.

Your other option is to only have one model to represent a reddit thread and have the $thread->comments attribute be of a serialized array. Read up on attribute casting in the Laravel documentation if you're curious.

//Collect the data to be stored in the DB
$allData=[];

$counter = 1; 


foreach ($posts as $post) {
    //foreach post get the data and store it in a database
    $allData[$counter]['title']= $post['data']['title'];

    //Foreach Title, get a sentiment using the sentiment analysis
    $sentiment = SentimentAnalysis::decision($allData[$counter]['title']);

    $allData[$counter]['created']= $post['data']['created'];

    //store this in the DB to have access to the information at a later stage
    RedditPosts::create([
            'title' => $allData[$counter]['title'], 
            'created' => date($allData[$counter]['created']),
            'sentiment' => $sentiment,
            'search_identifier' => $search_id,
            'search_phrase' => $searchPhrase
            ]);

    $allData[$counter]['comments'] = explode(PHP_EOL, $post['data']['selftext_html']);

    foreach($allData[$counter]['comments'] as $comment) {

        $sentiment = SentimentAnalysis::decision($comment);

              //store this in the DB to have access to the information at a later stage
              RedditComments::create([
                'comment' => strip_tags(html_entity_decode($comment)),
                'created' => date($allData[$counter]['created']),
                'sentiment' => $sentiment,
                'search_identifier' => $search_id,
                'search_phrase' => $searchPhrase
                ]);
           }

    $counter ++;
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM