我将一个数据数组从AngularJS传递给PHP,最后得到以下数组:
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
}
]
我怎样才能设法循环播放它以最终显示如下产品列表:
<li>Name1 (1)</li>
<li>Name2 (3)</li>
我尝试过以下但没有运气:
foreach ($products as $value) {
echo "<li>". $value->product ." (". $value->number .")</li>";
}
这是我在做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)
}
}
由于我已经初步解码了JSON,这就是最终的工作:
foreach ($products as $product) {
echo "<li>". $product->product ." (". $product->number .")</li>";
};
答案 0 :(得分:4)
由于它是一个数组,请尝试以下方法:
wrap_content
答案 1 :(得分:1)
您可以尝试:
$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>";
}
你可以在这里试试: http://sandbox.onlinephpfunctions.com/code/53394eb416be1727398f02e8a0adac68a5ce424e