我試圖將 json 轉換為 PHP 中的文本所以我的舊問題已關閉,我沒有得到答案。
這是我的代碼。從 Mysql 獲取:
<?php
$result_inventory = $con2->query("SELECT inventory FROM players WHERE id = '" .$selectedprofile["id"]."'");
$inventory_array = [];
while ($inventory_data = $result_inventory->fetch_assoc()) {
$inventory_array[] = $inventory_data;
}
?>
顯示結果:
<?php
$obj = json_encode($result_inventory);
foreach($obj as $inventory){
?>
<tbody>
<tr>
<td>
<div class="d-flex px-2 py-1">
<div>
<img src="" class="avatar avatar-sm me-3" alt="xd">
</div>
<div class="d-flex flex-column justify-content-center">
<h6 class="mb-0 text-sm"></h6>
</div>
</div>
</td>
<td>
<div class="text-xs font-weight-bold">
<?php echo $inventory['name'];?>
<h6 class="mb-0 text-sm"><?php echo $inventory['slot']; ?></h6>
</div>
</td>
<td class="text-xs font-weight-bold">
<span class="text-xs font-weight-bold"><?php echo $inventory['type']?></span>
</td>
<td class="text-xs font-weight-bold">
<span class="text-xs font-weight-bold"><?php echo $inventory['slot']?></span>
</td>
<td class="text-xs font-weight-bold">
<span class="text-xs font-weight-bold"><?php echo $inventory['amount']?></span>
</td>
</tr>
<tr>
</tr>
</tbody>
<?php }?>
</table>
訊息結果:
Invalid argument supplied for foreach()
我的資料庫:
[{"name":"phone","type":"item","slot":1,"amount":1,"info":[]},{"name":"driver_license","type":"item","slot":2,"amount":1,"info":{"birthdate":"1999-02-02","lastname":"Salem","type":"Class C Driver License","firstname":"Saleh"}},{"name":"id_card","type":"item","slot":3,"amount":1,"info":{"birthdate":"1999-02-02","gender":0,"citizenid":"TLT73227","nationality":"Saudi","lastname":"Salem","firstname":"Saleh"}},{"name":"lockpick","type":"item","slot":4,"amount":1,"info":[]}]
所以我想要這樣的結果:
<a>Name: Phone</a>
<a>Type: item</a>
<a>Slot: 1</a>
<a>Amount: 1</a>
所以我試圖得到結果,請幫我提取。
uj5u.com熱心網友回復:
我現在明白了。我假設每個組態檔 ID 只有 1 行。所以
$result_inventory = $con2->query("SELECT inventory FROM players WHERE id = '" . $selectedprofile["id"] . "'");
$inventory_array = [];
while ($inventory_data = $result_inventory->fetch_assoc()) {
$inventory_array[] = $inventory_data;
}
$json = $inventory_array[0]['inventory']; // if exists
$obj = json_decode($json, true);
// then continue with
foreach ($obj as $inventory) {
//...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/513506.html
標籤:phpmysqljson
