我刚开始学习PHP,我已经设法获得了我需要的JSON数据,但很难从JSON数据构建表。我知道我在试错时做错了,但现在卡住了。
到目前为止我的PHP:
<?php
............
$domains = json_decode(get_option('cc_whmcs_bridge_tlds'), true);
if (count($domains->pricing)) {
// Open the table
echo "<table>";
// Cycle through the array
foreach ($domains->pricing as $idx => $tld) {
// Output a row
echo "<tr>";
echo "<td>$tld->register[$idx]</td>";
echo "<td>$tld->transfer->[$idx]</td>";
echo "</tr>";
}
// Close the table
echo "</table>";
}
?>
JSON OUTPUT示例
{
"currency": {
"id": "1",
"code": "USD",
"prefix": "$",
"suffix": " USD",
"format": "2",
"rate": "1.00000"
},
"pricing": {
"com": {
"categories": [
"Popular",
"gTLD"
],
"addons": {
"dns": true,
"email": true,
"idprotect": true
},
"group": "new",
"register": {
"1": "9.95",
"2": "19.90",
"3": "29.85"
},
"transfer": {
"1": "9.95",
"2": "15.00",
"3": "25.00"
},
"renew": {
"1": "9.95",
"2": "15.00",
"3": "25.00"
}
},
"net": {
"categories": [
"Popular",
"gTLD"
],
"addons": {
"dns": false,
"email": false,
"idprotect": false
},
"group": "sale",
"register": {
"1": "9.00"
},
"transfer": {
"1": "11.95"
},
"renew": {
"1": "11.95"
}
},
"org": {
"categories": [
"Popular",
"gTLD"
],
"addons": {
"dns": false,
"email": false,
"idprotect": false
},
"group": "hot",
"register": {
"1": "11.95"
},
"transfer": {
"1": "11.95"
},
"renew": {
"1": "11.95"
}
}
}
}
我知道我的桌面PHP的东西完全错了,但正如我所说,第一次对我而言,这是我所得到的。
我试图渲染的表格如下:
TLD | REGISTER | TRANSFER | RENEW
---------------------------------------------
.com | 1yr (9.95) | 1yr (9.95) | 1yr (9.95)
.co.uk | 1yr (9.95) | 1yr (9.95) | 1yr (9.95)
等...
答案 0 :(得分:2)
你遇到的问题是循环中的元素不是数组,而是对象(stdClass
的实例,特别是)。您可以使用箭头操作符继续浏览它们:
$domains = json_decode($json);
foreach ($domains->pricing as $tld => $attrs) {
echo "<tr>";
echo "<td>".$tld."</td>";
echo "<td>1yr (".$attrs->register->{1}.")</td>";
echo "<td>1yr (".$attrs->transfer->{1}.")</td>";
echo "<td>1yr (".$attrs->renew->{1}.")</td>";
echo "</tr>";
}
你可以继续以同样的方式去做。例如,如果您需要显示每种类型的不同年份的所有价格选项,您可以在循环内添加:
foreach ($attrs->register as $nYears => $pricePerYear) {
echo $nYears." yrs: ".$pricePerYear;
}
您的另一个选项(更接近您最初的选项)是将true
设置为json_decode()
的第二个参数,它会为您提供array
而不是stdClass
1}}实例。此代码完成相同的操作:
$domains = json_decode($json, true);
foreach ($domains["pricing"] as $tld => $attrs) {
echo "<tr>";
echo "<td>".$tld."</td>";
echo "<td>1yr (".$attrs["register"][1].")</td>";
echo "<td>1yr (".$attrs["transfer"][1].")</td>";
echo "<td>1yr (".$attrs["renew"][1].")</td>";
echo "</tr>";
}
因此,您可以尝试以这种方式工作,无论哪种方式让您感觉更舒服。