【发布时间】:2016-01-11 00:52:58
【问题描述】:
假设我有以下 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 的方法。有没有办法在 PHP 中获取数组的“根”键的“名称”?
【问题讨论】:
-
foreach($items as $yourID => $item)见:php.net/manual/en/control-structures.foreach.php -
@Rizier123 感谢您的回答,它解决了我的问题!