Erik Figueiredo
Erik Figueiredo

Reputation: 325

Get JSON value from array in PHP

I have the following JSON

      [
           {
          "part_number": {
             "id": "1",
             "text": "962-00031-17A004"
          },
          "categoria": null,
          "codigo_cti": "",
          "fabricante": null,
          "modelo": null,
          "numero_serie": "",
          "obs": ""
       }
    ]

And I use the code bellow to collect data from it. If I select to extract obs, it works fine. I would like to know how can I collect the text and ID from part_number.

$produtos = json_decode($_POST['produtos'], true);  

foreach($produtos as $produto){
    echo $produto["obs"]; //WORKS FINE
    echo $produto["part_number"]["text"]; //DOES NOT WORK
}

Upvotes: 0

Views: 61

Answers (1)

CiaranSynnott
CiaranSynnott

Reputation: 928

Turn it into an object and not array first - its easier and Object Orientated is the way to go.

Here is a working example;

$json = '[
       {

      "part_number": {

         "id": "1",

         "text": "962-00031-17A004"

      },

      "categoria": null,

      "codigo_cti": "",

      "fabricante": null,

      "modelo": null,

      "numero_serie": "",

      "obs": ""

   }

]';

$produtos = json_decode($json, false);  


foreach($produtos as $produto){
   echo $produto->part_number->id;
}

Upvotes: 3

Related Questions