2

I'm passing an array of data from AngularJS to PHP, and I end up with the following array:

if(in_array('application/json', $contentType)) { // Check if Content-Type is JSON
  $data = json_decode($rawBody); // Then decode it
  $productes = $data->products;
} else {
  parse_str($data, $data); // If not JSON, just do same as PHP default method
}

products:[
  0:{
    product: "Name1",
    number: 1
  },
  1:{
    product: "Name2",
    number: 3
  }    
]

How could I manage to loop through it to end up displaying a list of products like so:

<li>Name1 (1)</li>
<li>Name2 (3)</li>

I've tried the following but no luck:

foreach ($products as $value) {
    echo "<li>". $value->product ." (". $value->number .")</li>";
}

This is what I get when I do var_dump($products):

array(4) {
  [0]=>
  object(stdClass)#2 (3) {
    ["product"]=>
    string(19) "Croissant d'ametlla"
    ["number"]=>
    int(1)
    ["preu"]=>
    float(1.95)
  }
  [1]=>
  object(stdClass)#3 (3) {
    ["product"]=>
    string(29) "Pain au chocolat (napolitana)"
    ["number"]=>
    int(1)
    ["preu"]=>
    float(1.4)
  }
  [2]=>
  object(stdClass)#4 (3) {
    ["product"]=>
    string(16) "Brioche de sucre"
    ["number"]=>
    int(1)
    ["preu"]=>
    float(1.2)
  }
  [3]=>
  object(stdClass)#5 (3) {
    ["product"]=>
    string(36) "Pa de blat egipci i integral (Xusco)"
    ["number"]=>
    int(1)
    ["preu"]=>
    float(4.45)
  }
}

SOLUTION

As I was already intially decoding the JSON, this is what ended up working:

foreach ($products as $product) {
  echo "<li>". $product->product ." (". $product->number .")</li>";
};
4
  • please try to var_dump($products) and share the result Commented Feb 22, 2017 at 15:29
  • @Mohammad see edit : ) Commented Feb 22, 2017 at 15:31
  • 1
    When you say "...but no luck", what output did you get? Was there an error? Did anything show at all? Commented Feb 22, 2017 at 15:46
  • @EricMitjans please have a look on this answer stdClass Object problems Commented Feb 22, 2017 at 15:47

2 Answers 2

4

As it's an array, give the following a try:

foreach ($products as $value) {
    echo "<li>". $value['product'] ." (". $value['number'] .")</li>";
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can try:

$json = '{"products":[{"product":"Name1","number":1},{"product":"Name2","number":3}]}';
$products = json_decode($json, TRUE)["products"];
foreach($products as $product) {
    echo "<li>{$product["product"]} ({$product["number"]})</li>";
}

You can try it here: http://sandbox.onlinephpfunctions.com/code/53394eb416be1727398f02e8a0adac68a5ce424e

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.