简体   繁体   中英

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
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM