我查看了各种答案,我假设这是由于缺少 foreach 循环,我只收到一个变量。共有 32 个类别,每个类别都有多个链接。
表结构:
CREATE TABLE `cattb` (
`catNo` int(11) NOT NULL,
`catName` varchar(100) NOT NULL,
PRIMARY KEY (`catNo`)
)
CREATE TABLE `linktb` (
`catId` int(11) NOT NULL,
`URL` varchar(255) NOT NULL,
`title` varchar(50) NOT NULL,
`description` longtext NOT NULL,
KEY `catId` (`catId`)
)
SQL查询:
SELECT catId, catName, URL, title, description FROM linktb, cattb WHERE linktb.catId=cattb.catNo
PHP:
while ($row = mysql_fetch_assoc($result)){
$json['categories'][] = array(
"catId"=> $row[catId],
"catName"=> $row[catName],
'links' => array(
"URL"=> $row[URL],
"title"=> $row[title],
"description"=> $row[description]
)
);
回复:
"categories":[
{"catId":"1",
"catName":"Career Resources",
"links":
{"URL":"http:\/\/www.designanddesign.com\/jobs.php",
"title":"Design & Design",
"description":"World-Wide Job Offers"
}
},
{"catId":"1",
"catName":"Career Resources",
"links":
{"URL":"https:\/\/www.nuans.com\/rts-str\/en\/home-accueil_en.cgi",
"title":"NUANS Report",
"description":"Naming A Company (Federal)"
}
}
我想看到的:
{ categories: [
{ catName: "Career Resources",
catId: "1",
links: [
{URL:"http://www.designanddesign.com/jobs.php",title:"Design & Design",description:"World-Wide Job Offers"},
{URL:"https://www.ic.gc.ca/app/scr/cc/CorporationsCanada/hm.html?locale=en_CA",title:"Corporations Canada",description:"Incorporating a Business"},
{URL:"http://lea.verou.me/css3patterns/",title:"CSS3 Patterns",description:"Patterns to use for backgrounds"},
{URL:"http://webdesignerwall.com/tutorials/cross-browser-css-gradient",title:"CSS Gradients",description:"Cross-browser Compatible"}
],
},
{ catName: "CSS",
catId: "2",
links: [
{URL:"http://www.designanddesign.com/jobs.php",title:"Design & Design",description:"World-Wide Job Offers"},
{URL:"https://www.ic.gc.ca/app/scr/cc/CorporationsCanada/hm.html?locale=en_CA",title:"Corporations Canada",description:"Incorporating a Business"},
{URL:"http://lea.verou.me/css3patterns/",title:"CSS3 Patterns",description:"Patterns to use for backgrounds"},
{URL:"http://webdesignerwall.com/tutorials/cross-browser-css-gradient",title:"CSS Gradients",description:"Cross-browser Compatible"}
],
}
我将如何为数组编写 for-each 循环?