我从数据库中检索此JSON:
{
"articles": {
"1": {"discription":"Transport", "tax":"21", "price":"234"
},
"2": {"discription":"Opslag", "tax":"19", "price":"19"}
}
}
接下来我要做的是从每个对象中检索描述,税款和价格,如何以最有效的方式为每个循环使用a?
谢谢!
答案 0 :(得分:5)
您可以使用以下代码段获取所提及键的值-
<?php
$str = '{
"articles": {
"1": {"discription":"Transport", "tax":"21", "price":"234"
},
"2": {"discription":"Opslag", "tax":"19", "price":"19"}
}
}';
//convert json to array
$jsonToArray = json_decode($str, true);
foreach ($jsonToArray['articles'] as $value) {
echo $value['discription'] . ' ' . $value['tax'] . ' ' . $value['price'] . PHP_EOL;
}
如果要使用对象访问这些键,则可以继续执行以下代码段-
<?php
$str = '{
"articles": {
"1": {"discription":"Transport", "tax":"21", "price":"234"
},
"2": {"discription":"Opslag", "tax":"19", "price":"19"}
}
}';
//convert json to object
$jsonToObject = json_decode($str);
foreach ($jsonToObject->articles as $value) {
echo $value->discription . ' ' . $value->tax . ' ' . $value->price . PHP_EOL;
}
您可以根据自己的需要在echo
语句中进行更改。
答案 1 :(得分:1)
$array = json_decode($json_string);
for($i = 0; $i<sizeof($array); $i++) {
echo $array[$i]['description'];
echo $array[$i]['tax'];
echo $array[$i]['price'];
}