如何使用PHP设计数组结构并将其编码为Json? [英] How to design an Array Structure and Encode to Json using PHP?
本文介绍了如何使用PHP设计数组结构并将其编码为Json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在MySql中有2个表
I have 2 tables in MySql
部分
ID Name
=====================
1 Section1
2 Section2
类别
ID SectionID Name
=========================================
1 1 Category1
2 1 Category2
3 2 Category3
这就是我现在拥有的:
This is what I have now:
$sql_section = "select * from section";<br>
$sql_category = "select * from category";<br>
$result_section = mysql_query($sql_section) or die("Could not execute query.");
$result_category = mysql_query($sql_category) or die("Could not execute query.");
echo json_encode(???????);
我想用PHP编码JSON以得到如下所示的结果:
And I would like to Encode JSON in PHP to get the result that looks like this:
{sections:[
{sectionName: "Section1", categoryList: [{categoryName: "category1"},
{categoryName: "category2"}]},
{sectionName: "Section1", categoryList: [{categoryName: "category3"}]}<br>
]}
关于如何设计看起来像这样的数组的任何线索?
Any clue of how can I design an array that looks like this?
推荐答案
$arr = array('sections' => array());
$arr['sections'][] = array('sectionName' => array('categoryList' => array( array('categoryName' => 'Category 1'), array('categoryName' => 'Category 2'))));
$arr['sections'][] = array('sectionName' => array('categoryList' => array( array('categoryName' => 'Category 3'), array('categoryName' => 'Category 4'))));
echo json_encode($arr);
输出://
{"sections":[
{"sectionName":
{"categoryList":
[{"categoryName":"Category 1"},
{"categoryName":"Category 2"}]}
},
{"sectionName":
{"categoryList":
[{"categoryName":"Category 3"},{"categoryName":"Category 4"}]}}]}
您只需要用变量替换字符串值,然后将其放入循环中即可创建所需的数据集.
You'll just need to replace the string values with variables and put it in the loop to create the required data set.
这篇关于如何使用PHP设计数组结构并将其编码为Json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文