我需要得到一个带有数组的 JSON,我该怎么做?
//JSON I need to get
{"keywords":[{"keyword":"kw1", "tags":["sample"]},{"keyword":"kw2", "tags":["sample, sample2"]}]}
//For now, I got this
$keywords = array("kw1", "kw2");
$tags= array("sample", "sample2");
function Keywords($keywords, $tags){
$fields= array("keywords" => $keywords);
$jsondata = json_encode($fields);
print_r($jsondata );
}
//output
{"keywords":["kw1","kw2"]}
我希望输出是这样的:
{"keywords":[{"keyword":"kw1", "tags":["sample"]},{"keyword":"kw2", "tags":["sample, sample2"]}]}
假设tags
你的例子的第一个元素也应该是["sample, sample2"]
(否则你真的必须解释你想要在结果中实现什么逻辑)......
$keywords = array("kw1", "kw2");
$tags= array("sample", "sample2");
$result = new StdClass;
$result->keywords = [];
foreach($keywords as $keyword) {
$temp = new StdClass;
$temp->keyword = $keyword;
$temp->tags = [];
foreach($tags as $tag) {
$temp->tags[] = $tag;
}
$result->keywords[] = $temp;
}
echo json_encode($result);
基本上是关键字和标签上的两个嵌套循环,并在一个新的临时对象中创建一个然后附加到结果数组中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句