2

I am using json_decode and echoing the values using a nested foreach loop.

Here's a truncated json that I am working on:

[{"product_name":"Product 1","product_quantity":"1","product_price":"2.99"},....

and the loop

foreach($list_array as $p){
    foreach($p as $key=>$value) {
        $result_html .= $key.": ".$value."<br />";
    }
}

This was I am able to echo all key/value pairs.

I have tried using this to echo individual items something like:

foreach($list_array as $p){
    foreach($p as $key=>$value) {
        echo "Product: ".$p[$key]['product_name'];
        echo "Quantity: ".$p[$key]['product_quantity'];
    }
}

However I am unable to because it doesn't echo anything.

I would like to be able to show something like:

Product Name: Apple

Quantity: 7

Currently it is showing:

product_name: Apple

product_quantity: 7

How can I remove the key and replace it with a predefined label.

Abu Nooh
  • 846
  • 4
  • 12
  • 42
  • @Terminus I've updated the question with example code I've tried. – Abu Nooh Sep 17 '17 at 19:02
  • Try to do `var_dump($list_array)` to see what you've go from json_decode. Maybe you don't get the correct data. – astax Sep 17 '17 at 19:05
  • @astax I did however not entirely sure. I have added in the above too. – Abu Nooh Sep 17 '17 at 19:10
  • Thanks for updating it. But this is a source string rather than decoded data. Do you have a code like `$list_array = json_decode($data);` ? Add `var_dump($list_array);` after it. – astax Sep 17 '17 at 19:14
  • @astax here's the result of var dump array(3) { [0]=> object(stdClass)#1 (5) { ["product_name"]=> string(9) "Product 1" ["product_quantity"]=> string(1) "1" ["product_price"]=> string(4) "2.99" – Abu Nooh Sep 17 '17 at 19:21

2 Answers2

2

It can be done with:

foreach ($list_array as $p){
    $result_html .= 'Product: ' . $p->product_name 
        . 'Quantity: ' . $p->product_quantity . '<br />';
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
1

If you are decoding your json into an object you can do it like that.

$list_array = json_decode('[{"product_name":"Product 1","product_quantity":"1","product_price":"2.99"}]');

$result_html = '';
foreach($list_array as $p){
    $result_html .= '<div>Product: '.$p->product_name.'</div>';
    $result_html .= '<div>Quantity: '.$p->product_quantity.'</div>';
}
echo $result_html;
Johnny Dew
  • 971
  • 2
  • 13
  • 29