doumen5491 2017-02-24 08:59
浏览 87
已采纳

如何在PHP中存储特定的JSON数据并摆脱未定义的索引通知?

I'm developing an app using PHP and I'm fetching data via api endpoint. I was able to get the data I want - a huge chunk of it, found here: https://gist.github.com/kamaelxiii/18ef0c1600330b98717b96db00532d6a

Now my blocker is I just want to get and store the specific ID of a player (look for name : kamaelxiii) my code was able to get the ID but the page also displays this message:

Notice: Undefined index: name in C:\xampp\htdocs\vgapp\index.php on line 230

I'm thinking that this is because I'm looping to the entire included block but not all contains the index name in it. I've tried adding break inside the for loop below but the ID that I'm after is not always the first in the list so there are times that the message above still shows - most of the time.

Here's my line of code that gets the specific ID:

if(is_array($finaljson) || is_object($finaljson)){
foreach ($finaljson['included'] as $key => $value) {
        if($value['attributes']['name'] === $username){
            $userid = $value['id'];
        }
}
  • 写回答

2条回答 默认 最新

  • douyi8732 2017-02-24 09:07
    关注

    If you want to get rid of Notice, Then just use empty() or isset() in your foreach loop's if condition. below is the code.

     if(is_array($finaljson) || is_object($finaljson)){
     foreach ($finaljson['included'] as $key => $value) {
     //you can use empty check 
        if(!empty($value['attributes']['name']) && $value['attributes']['name'] === $username){
                $userid = $value['id'];
        }
    //or you can use isset 
       if(isset($value['attributes']['name']) && $value['attributes']['name'] === $username){
                $userid = $value['id'];
        }
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog