0

we are developing a PHP project where we are parsing a JSON object which is multidimensional. We are unable to access a variable value using a key value pair method using foreach.

Response which need to be parsed:

{
    "cash_pickups_count": 0.0,
    "cod_count": 0,
    "success": false,
    "package_count":         1,
    "upload_wbn": "UPL11355346020539699686",
    "replacement_count": 0,
    "cod_amount": 0.0,
    "prepaid_count": 0,
    "rmk": "An internal Error has occurred, Please get in touch with client.support@delhivery.com",
    "pickups_count": 0,
    "packages": [
        {
            "status": "Fail",
            "waybill": "6009910000136",
            "serviceable": false,
            "refnum": "26399",
            "client": "INKDAD",
            "remarks": ["Duplicate order id"],
            "sort_code": null,
            "cod_amount": 0.0,
            "payment": "Pre-paid"
        }
    ],
    "cash_pickups": 0.0
}

Code via which we are parsing:

$res = json_decode($result,true);
foreach ($res as $key => $val) {
  echo $key;

  if(($key) == "packages")
  {
      echo "entered in this loop";
      foreach($val as $key1 => $value){
          echo $key1;           
          if(($key1)== "waybill"){
            $waybill = ;
            echo $waybill;
            }
        }
    }
}

We are getting an Array to string operation error.

Can you please let us know what is an issue over here?

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • Please do a google search before asking – RiggsFolly Jan 21 '17 at 16:05
  • @RiggsFolly This is *not* a duplicate. Please read the question more carefully. – Olaf Dietsche Jan 21 '17 at 16:25
  • @Apu The value of "packages" is an array and you're iterating this array in the inner for loop. To access "waybill" in this inner loop, you must say `$waybill = $value['waybill'];`. And you don't need the `if`, which is wrong anyway, read http://php.net/manual/de/language.types.string.php#language.types.string.conversion for this. – Olaf Dietsche Jan 21 '17 at 16:35

0 Answers0