我想将HTML ul列表转换为json格式。
html列表采用以下格式:
<li><span class="orgname">Adams Center Free Library</span> <span class="status">Closed</span></li>
<li><span class="orgname">Weight Watchers Watertown</span> <span class="status">Delayed</span></li>
我希望它是这样的json格式:
{
"meta": {
"closed_count": "1",
"delayed_count": "1"
},
"list": [
{
"data": {
"orgname": "Adams Center Free Library",
"status": "Closed"
}
},
{
"data": {
"orgname": "Weight Watchers Watertown",
"status": "Delayed"
}
}
]
}
有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
我假设您正在从某个数据库输出数据。因此,将值添加到数组,然后编码为json:
$delayed = 0;
$close = 0;
$data = [];
echo "<ul>";
foreach ($myArray as $row) {
echo "<li><span class='orgname'>{$row['orgname']}</span> <span class='status'>{$row['status']}</span></li>";
$data[] = ['data' => ['orgmane' => $row['orgname'], 'status' => $row['status']]];
// or if $row only has 'orgname' and 'status'
$data[] = ['data' => $row];
if (strtolower($row['status']) == 'delayed') {
$delayed++;
} else {
$closed++;
}
}
echo "</ul>";
json_encode(
[
'meta' => ['closed_count' => $closed, 'delayed_count' => $delayed],
'list' => $data,
]
);