运行复杂的json并匹配文本

时间:2017-04-01 11:01:25

标签: php json

我想运行reddit注释并将json与特定文本匹配:

我尝试了以下

$str = json_decode(file_get_contents('https://www.reddit.com/r/all/comments.json'));
foreach ($str as $comments) {
    //dd($comments->data->children);
    foreach ($comments->data->children as $comment) {
        if ($comment->body_html == 'You') {
            print_r($comment);
        } else {
            print_r($comment);
        }
    }
}

但是,我收到以下错误消息:

  [ErrorException]                      
  Trying to get property of non-object  


Exception trace:
 () at /home/ubuntu/workspace/app/Console/Commands/reddit.php:58
 Illuminate\Foundation\Bootstrap\HandleExceptions->handleError() at /home/ubuntu/workspace/app/Console/Commands/reddit.php:58
 App\Console\Commands\reddit->handle() at n/a:n/a
 call_user_func_array() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Container/Container.php:507
 Illuminate\Container\Container->call() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:169
 Illuminate\Console\Command->execute() at /home/ubuntu/workspace/vendor/symfony/console/Command/Command.php:256
 Symfony\Component\Console\Command\Command->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:155
 Illuminate\Console\Command->run() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:794
 Symfony\Component\Console\Application->doRunCommand() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:186
 Symfony\Component\Console\Application->doRun() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:117
 Symfony\Component\Console\Application->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:107
 Illuminate\Foundation\Console\Kernel->handle() at /home/ubuntu/workspace/artisan:36

我希望使用$comments->data->children来访问body_html标记,但它不起作用。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

在您的情况下,str不是数组而是对象。它是如何运作的:

$str = file_get_contents('https://www.reddit.com/r/all/comments.json');
$comments = json_decode($str);
foreach ($comments->data->children as $comment) {
        if ($comment->data->body_html == 'You') {
            print_r($comment);
        } else {
            print_r($comment);
        }
}

答案 1 :(得分:0)

在这种情况下,json_decode函数的输出是一个数组,而不是一个对象。因此您无法通过$comments->data->children访问它。相反,您可以通过以下方式访问它:$comments["data"]["children"]

如果您希望json_decode生成对象作为输出,请使用第二个参数true

$str = json_decode(file_get_contents('https://www.reddit.com/r/all/comments.json'), true);