Kamruddin Bivob Kamruddin Bivob - 4 months ago 8
JSON Question

how to validate a json empty object in php

my php code works fine when it returns the result like this ->

{
"id": 267935,
"results": [
{
"key": "rc94yWXcyr0",
"name": "Trailer 1",
"site": "YouTube"
},
{
"key": "GZ0Bey4YUGI",
"name": "Official Trailer",
"site": "YouTube"
},
{
"key": "y1fZg0hhBX8",
"name": "Official Trailer 2",
"site": "YouTube"
}
]
}


but i get error


(Notice: Undefined variable: finaltrailers in ... )


when results return like this -->

{
"id": 392344,
"results": [

]
}


and this is my php code -->

$trailer = $json2['results'];
foreach($trailer as $trailers=>$keytrailers){
foreach($keytrailers as $alltrailers=>$allkeytrailers){
if($alltrailers == 'key'){
@ $finaltrailers .= $allkeytrailers.',';
}
}
}
echo trim($finaltrailers,",");


how can i validate the empty array and give and error my self ? please help me thank you.

Answer

You have to define the variable to use it in trim. Just add it at the beginning of your code.

$finaltrailers = '';
$trailer = $json2['results'];

foreach($trailer as $trailers=>$keytrailers){
    foreach($keytrailers as $alltrailers=>$allkeytrailers){
        if($alltrailers == 'key'){
             @ $finaltrailers .=  $allkeytrailers.',';
        }
     }
}
echo trim($finaltrailers,",");
Comments