Cyberpunk7711
Cyberpunk7711

Reputation: 129

PHP handle error message when data is pulled from json

I have a simple question. I have different returnvalues (jsons) but one class for all. if a value is not included in the json, i get an error message: Notice: Undefined index how do i get a query, but no error message. if the value is not assigned, for example -1 should be entered.

JSON:

Array
(
    [number] => 2
    [name] => Aachen-Rothe Erde
    [mailingAddress] => Array
        (
            [city] => Aachen
            [zipcode] => 52066
            [street] => Beverstr. 48
        )

    [category] => 4
    [priceCategory] => 4
    [hasParking] => 1
    [hasBicycleParking] => 1
    [hasLocalPublicTransport] => 1
    [hasPublicFacilities] => 
    [hasLockerSystem] => 
    [hasTaxiRank] => 1
    [hasTravelNecessities] => 
    [hasSteplessAccess] => yes
    [hasMobilityService] => no
    [hasWiFi] => 
    [hasTravelCenter] => 
    [hasRailwayMission] => 
    [hasDBLounge] => 
    [hasLostAndFound] => 
    [hasCarRental] => 
    [federalState] => Nordrhein-Westfalen
)

PHP:

 $return = json_decode($file, true);
    $back = array();
    $array = array();
    for ($i = 0; $i < 100; $i++) {
        $array[] = $return['result'][$i];
        //$back[] = new GetMatchesForTrainstationSearch($array[$i]);
    }
    echo $input['something that is not in json'];

Upvotes: 1

Views: 50

Answers (2)

Tropen
Tropen

Reputation: 125

Previous answer is good. I can add, that you can avoid "undefined index" error by using foreach-loop, which will go only by indexes which exist in your array:

$return = json_decode($file, true);
if (json_last_error() === JSON_ERROR_NONE) {
return 'error msg or msg type';
}

$result = [];
if (is_array($return))
{
    foreach ($return as $k => $v)
    {
    //use it as $return[$k] = $v; 
     if ($v > 0) $result[] = $v;

     return $result;
    }
}

return 'error';

Upvotes: -1

ArSeN
ArSeN

Reputation: 5258

One option would be to continue the loop if the index you are trying to access does not exist:

for ($i = 0; $i < 100; $i++) {
    if (!isset($return['result'][$i])) {
        continue;
    }
    $array[] = $return['result'][$i];
}

Upvotes: 2

Related Questions