0

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
}
6
  • 2
    Try dumping the $produto variable using var_dump($produto) to see all the values in the array. Commented Nov 17, 2015 at 10:56
  • part_number is not the key, it's inside another object without a key Commented Nov 17, 2015 at 10:57
  • WFM 3v4l.org/L7juj Commented Nov 17, 2015 at 10:59
  • I see its working. Try using echo '<pre>';print_r($produtos); Commented Nov 17, 2015 at 11:04
  • For me its working. echo $produto["part_number"]["text"]; . Commented Nov 17, 2015 at 11:07

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

How does this help? The only difference is that objects aren't converted. If it's not working with arrays, there's probably the same issue with using them as objects.
@JonStirling Objects are much easier to deal with then arrays when converting JSON
@JamieSterling Thanks for the example
@CiaranSynnott, thanks for your answer. It worked fine!
@CiaranSynnott That's not the point. Imo, the example doesn't really change anything other than how you access stuff.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.