-1

i have the following Json sent via ajax to test.php:

[{},{"product[]":"john","qty[]":"12","price[]":"100","total[]":"1200"},{"product[]":"juan","qty[]":"22","price[]":"3.5","total[]":"77"},{"product[]":"louis","qty[]":"99","price[]":"1.22","total[]":"120.78"},{"product[]":"paul","qty[]":"5","price[]":"2.1","total[]":"10.5"},{"product[]":"carl","qty[]":"9","price[]":"14","total[]":"126"},{"total_amount":"1533.00"}]

In my php file I am trying to loop through each individual product[], qty[], price[] and list values:

<?php
    $obj = json_decode($_POST["mydata"]);
    header('Content-Type: application/json');

   // echo json_encode($obj[1]->{'product[]'}); //(works)


foreach($obj as $item) {


echo $item['product[]'].'<br>';
echo $item['price[]'].'<br>';
echo $item['qty[]'].'<br>';
echo $item['total[]'].'<br>';     
     }

?>

but this throws an error. What is wrong in my loop?

R_life_R
  • 786
  • 6
  • 26

2 Answers2

1

There are a couple of things wrong with the code, the first is that you decode as objects and try and use this as an array. You need to pass true as the second parameter to json_decode() to make it an associative array.

The second is that your array contains elements which don't have all of the details. The last element only has "total_amount", so none of the other fields exist. This is why I use

if ( isset($item['product[]'])){

to check the object before outputting the data...

$obj = json_decode($_POST["mydata"], true);
header('Content-Type: application/json');

foreach($obj as $item) {
    if ( isset($item['product[]'])){
        echo $item['product[]'].'<br>';
        echo $item['price[]'].'<br>';
        echo $item['qty[]'].'<br>';
        echo $item['total[]'].'<br>';
    }
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
0

Pass true as second argument to json_decode.

Per the documentation:

assoc

When TRUE, returned objects will be converted into associative arrays.

So your code becomes:

$obj = json_decode($_POST["mydata"], true);

Also note that the first entry in your array is empty, so you're gonna have to check for that.

Community
  • 1
  • 1
Jeto
  • 14,596
  • 2
  • 32
  • 46