我有一個JSON,我需要提取標題和數據inot一個包含頂部和左側標題的html表格。我已經提供了表格數據的一個片段。任何人都可以請幫助分解foreach的邏輯,以便能夠顯示html corrcetly。用左和右頂部標題創建表格JSON數據
$json ='{
"jform": {
"product": ["3", "4"],
"type": "101"
},
"mainheading": "TYPICAL ANALYSIS",
"heading1": "NatraMin Original",
"heading2": "NatraMin Cal-S",
"heading3": "NatraMin Cal-K",
"heading4": "",
"heading5": "",
"heading6": "",
"heading7": "",
"heading8": "",
"maindata": ["Calcium", "Phosphorus"],
"data1": ["c12%", "p12%"],
"data2": ["c13%", "p13%"],
"data3": ["c14%", "p14%"],
"data4": ["", ""],
"data5": ["", ""],
"data6": ["", ""],
"data7": ["", ""],
"data8": ["", ""],
"itemid": "2"
}';
$tableData = json_decode($json);
foreach ($tableData as $key => $value) {
echo $key.':'.$value.'<br/>';
}
以下代碼段僅僅是用來創建在其下方TEH試樣臺screengrab的HTML IM。我需要以某種方式將該html的各個部分改爲foreach。我試圖嵌套的foreach,但只是搞砸了,因此爲什麼我已經刪除了我的trys,只是儘可能乾淨地提供代碼。
echo '
<style>
table {}
table td.top { padding: 10px; background-color: red;color: white}
table th.top { padding: 10px; background-color: blue; color: white}
table th.side { padding: 10px; background-color: green; color: white}
table td { padding: 10px; border-bottom:1px solid #ededed; text-align:center;}
</style>
<table class="table">
<tbody>
<tr>
<th class="top" >TYPICAL ANALYSIS</th>
<td class="top" >NatraMin Original</td>
<td class="top" >NatraMin Cal-S</td>
<td class="top" >NatraMin Cal-K</td>
</tr>
<tr>
<th class="side" >Calcium</th>
<td>c12%</td>
<td>c13%</td>
<td>c14%</td>
</tr>
<tr>
<th class="side" >Phosphorus</th>
<td>p12%</td>
<td>p13%</td>
<td>p14%</td>
</tr>
</tbody>
</table>';
當我運行phptester.net最高層的代碼片段,我得到下面的輸出,我不是太擔心空值,我只是需要確保包含數據的值正確匹配桌子。
Error Object of class stdClass could not be converted to string on line number 33
jform:
mainheading:TYPICAL ANALYSIS
heading1:NatraMin Original
heading2:NatraMin Cal-S
heading3:NatraMin Cal-K
heading4:
heading5:
heading6:
heading7:
heading8:
maindata:Array
data1:Array
data2:Array
data3:Array
data4:Array
data5:Array
data6:Array
data7:Array
data8:Array
itemid:2
感謝提前:) 約翰
這是因爲jform解碼到一個對象,而不是一個字符串。你可以檢查並跳過它,如果你想通過使用'if_object($ value)' –
我建議你將'JSON'轉換爲數組,而不是使用'true'作爲第二個參數。即:_' $ tableData = json_decode($ json,true);'_ –
@RyanVincent謝謝,這確實解決了錯誤。我仍然需要知道如何在我的foreach中顯示html表格。你能幫忙嗎? –