假设我有以下JSON文件:
{
"item_a_id":{
"title":"...",
"description":"..."
},
"item_b_id":{
"title":"...",
"description":"..."
}
}
我使用json_decode()
函数创建一个数组,稍后将使用该数组创建包含每个项目及其各自属性的表格,最好采用以下格式:
ID | Title | Description |
----------|--------------|--------------------|
item_a_id | item_a_title | item_a_description |
item_b_id | item_b_title | item_b_description |
为此,我编写了以下PHP代码:
// Load JSON data into array
$items = json_decode ($json_string, true);
// Begin the HTML table
echo "<table>";
// Add a row with information of each item
foreach ($items as $item) {
echo "<tr>";
echo "<td>" . "ID should go here..." . "</td>";
echo "<td>" . $item['title'] . "</td>";
echo "<td>" . $item['description'] . "</td>";
echo "</tr>";
}
// End table
echo "</table>";
虽然正确加载了每个项目的标题和描述,但我似乎找不到获取项目ID的方法。有没有办法得到这个名字&#39; &#39; root&#39; PHP中数组的键?
答案 0 :(得分:1)
获取密钥和值的foreach模式如下:
foreach ($items as $key => $value){
echo "<tr>";
echo "<td>" . $key . "</td>";
echo "<td>" . $value['title'] . "</td>";
echo "<td>" . $value['description'] . "</td>";
echo "</tr>";
}