我编码了一些存储在mysql数据库中的值。我想解码它们以使用PHP在桌面上显示。
我正在使用的示例查询:
$sql = "SELECT `coc_id`, `cc_id`, `category_options`FROM
`ag_category_option_combos` WHERE coc_id='831'";
$result = $con->query($sql);
while ($row = $result->fetch_assoc()) {
# code...
// $data = array();
$data = json_decode($row['category_options'], true);
echo ' <tr>
<td>' . $row['coc_id'] . '</td>
<td>' . $row['cc_id'] . '</td>
<td>' . $data['id'] .'</td>
<td>' . $data['name'] .'</td>
</tr>';
print_r($data);
echo $data;
}
示例数据库中的mysql数据:
----+---------------------+------------+
| coc_id | cc_id | category_options | created_at | updated_at |
+--------+-------+----------------------------------------------------------------------------------------------------------+---------------------+------------+
| 16 | 15 | {"categoryOption":{"id":"13","name":"default"}} | 2018-03-19 09:42:06 | |
| 825 | 824 | {"categoryOption":[{"id":"798","name":"<15"},
{"id":"821","name":"Male"}]} | 2018-03-19 09:42:06 | |
| 826 | 824 | {"categoryOption":[{"id":"798","name":"<15"},{"id":"822","name":"Female"}]} | 2018-03-19 09:42:06 | |
| 827 | 824 | {"categoryOption":[{"id":"799","name":"15 - 24"},{"id":"821","name":"Male"}]} | 2018-03-19 09:42:06 | |
| 828 | 824 | {"categoryOption":[{"id":"799","name":"15 - 24"},{"id":"822","name":"Female"}]} | 2018-03-19 09:42:06 | |
| 829 | 824 | {"categoryOption":[{"id":"800","name":"25 - 34"},{"id":"821","name":"Male"}]} | 2018-03-19 09:42:06 | |
| 830 | 824 | {"categoryOption":[{"id":"800","name":"25 - 34"},{"id":"822","name":"Female"}]} | 2018-03-19 09:42:06 | |
我现在想要的是每行显示coc_id和cc_id列上的所有项目,但是category_options中的一个值数组和下一行中的另一个数组
示例:使用上面示例mysql数据中的第2行
<tr>
<td>825</td>
<td>824</td>
<td>798</td>
<td><15</td>
</tr>
<tr>
<td>825</td>
<td>824</td>
<td>821</td>
<td>Male</td>
</tr>
我如何做到这一点? 或者,如果有更好的方法,请提供建议
答案 0 :(得分:1)
您可以遍历JSON中的所有元素,重复<tr>
标记:
$data = json_decode($row['category_options'], true);
// Fix if $data['categoryOption'] is not an "array" of elements
if (isset($data['categoryOption']['id'])) {
$data['categoryOption'] = [$data['categoryOption']];
}
// loop over $data['categoryOption'] array of the JSON:
foreach ($data['categoryOption'] as $item) {
echo '<tr>
<td>' . $row['coc_id'] . '</td>
<td>' . $row['cc_id'] . '</td>
<td>' . $item['id'] . '</td>
<td>' . $item['name'] .'</td>
</tr>';
}