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>";
};
var_dump($products)and share the result