如何在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'];
}
}
我正在使用PHP开发一个应用程序,我正在通过api端点获取数据。 我能够获得我想要的数据 - 这里有很大一部分,可以在这里找到: https:// gist .github.com / kamaelxiii / 18ef0c1600330b98717b96db00532d6a p>
现在我的拦截器是我只想获取并存储播放器的特定ID(查找名称:kamaelxiii)我的代码是 能够获取ID但页面也显示以下消息: p>
注意: strong>未定义的索引: C:\ xampp \ htdocs \ vgapp \中的名称 第230行的index.php strong> p>
我认为这是因为我循环到整个 这是获取特定ID的代码行: p>
included code>块,但并非所有包含 索引
name code>。 我已经尝试在下面的for循环中添加
break code>但是我所追求的ID并不总是列表中的第一个,所以有时候上面的消息仍然显示 - 大部分时间。 p>
if(is_array($ finaljson)|| is_object($ finaljson) ){
foreach($ finaljson ['included'] as $ key => $ value){
if($ value ['attributes'] ['name'] === $ username){
$ userid = $ value ['id'];
}
}
code> pre>
div>
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'];
}
}
It is not a serious problem.
error_reporting(0);
OR:
if(@$value['attributes']['name'] === $username){
$userid = $value['id'];
}