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.

5
  • @Terminus I've updated the question with example code I've tried. Commented Sep 17, 2017 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. Commented Sep 17, 2017 at 19:05
  • @astax I did however not entirely sure. I have added in the above too. Commented Sep 17, 2017 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. Commented Sep 17, 2017 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" Commented Sep 17, 2017 at 19:21

2 Answers 2

2

It can be done with:

foreach ($list_array as $p){
    $result_html .= 'Product: ' . $p->product_name 
        . 'Quantity: ' . $p->product_quantity . '<br />';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for that I got a fatal error: Cannot use object of type stdClass as array. Found the solution none the less!
Okay, I changed [] notation to ->.
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;

Comments

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.