doubu1970 2018-05-19 13:43
浏览 57
已采纳

PHP - 从JSON数组中获取变量

I am using a PHP library (Abraham's OAUTH) as an app to connect to my twitter account and I am pulling down my own tweets from Twitter's API in an attempt to aesthetically display them on my on page.

I'm looping through them all with a foreach

<?php

foreach ($statuses as $key => $status) {
    echo '
    <blockquote class="twitter-tweet" data-lang="en"><p lang="und" dir="ltr">' . $status->text . '</p>
    ' . $status->name . ' (@' . $status->screen_name . ') <a href="https://twitter.com/' . $status->screen_name . '/status/' . $status->id_str . '">' . $status->created_at . '</a></blockquote><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script><br>
    ';
}

?>

These are the from the var_dump and are the ones I am using

array(1) { [0]=> object(stdClass)#3 (25) { ["created_at"]=> string(30) "Fri May 18 10:41:07 +0000 2018" ["id"]=> int(997426852204634112) ["id_str"]=> string(18) "997426852204634112" ["text"]=> string(27) "lol" ["name"]=> string(6) "Example" ["screen_name"]=> string(10) "Example_Name"

However I get returned:

Notice: Undefined property: stdClass::$name

Notice: Undefined property: stdClass::$screen_name

Why is this? I see name and screen_name in the var_dump so why is it not able to pick them up?

  • 写回答

1条回答 默认 最新

  • douzhuangxuan3268 2018-05-19 13:58
    关注

    It's simply a notice, marking that the structure has no property. You have several solutions:

    1. Switch Notice error off (Not recommended) Official php docs
    2. Check if the property exists and echo it only if it does. E.g.:

      isset($status->screen_name) ? $status->screen_name : '';
      
    3. You can normalize data before output: just initialize the property with a default value if it doesn't exist:

       $status->screen_name = isset($status->screen_name) ? $status->screen_name : '';
      

    Update: In your case you try to access the wrong node: "screen_name" is a node of the stdClass object user, which is a child of your status object. So, you need to call $status->user->screen_name.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问