更新:我更改了代码如下
$cats = get_categories();
$output = array(\'categories\' => array());
function collect_posts(){
$args = array( \'numberposts=\' => 9999, \'category\' => $cat );
$myposts = get_posts( $args );
foreach( $myposts as $post ) {
setup_postdata($post);
if (get_post_meta($post->ID, \'apls_video_youtube\', true) != \'\'){
$url = \'http://www.youtube.com/watch?v=\';
$url .= get_post_meta($post->ID, \'apls_video_youtube\', true);
} else {
$url = get_post_meta($post->ID, \'apls_video_hosted\', true);
}
$output[\'posts\'][] = array(
\'name\' => get_the_title($post->ID),
\'url\' => $url,
);
return $output;
}
}
foreach ($cats as $cat) {
$output[\'categories\'][] = array(
\'cat_id\' => $cat->term_id,
\'cat_name\' => $cat->name,
collect_posts()
);
}
header("Content-type: application/json");
die(json_encode($output));
输出为:
{
"categories": [
{
"cat_id": "555",
"cat_name": "Articles",
"0": {
"posts": [
{
"name": "title",
"url": "http://www.domain.com......."
}
]
}
},
{
"cat_id": "15",
"cat_name": "Crank",
"0": {
"posts": [
{
"name": "title examlple",
"url": "http://www.domain.com/v......"
}
]
}
},
{......
问题是:
仅显示一篇文章在每个类别中显示同一篇文章添加了0(零)
所以我需要你的建议来解决这个问题。
============================上一部分=========================
我想得到json输出
{
"categories": [
{
"cat_id": "16",
"cat_name": "Arm Lock",
"posts": [
{
"name": "Video1",
"url": "http://www.videourl1.com/"
},
{
"name": "Video2",
"url": "http://www.videourl2.com/"
},
{
"name": "Video2",
"url": "http://www.videourl3.com/"
}
]
},
{
"cat_id": "12",
"cat_name": "Kick",
"posts": [
{
"name": "Video1",
"url": "http://www.videourl3.com/"
},
{
"name": "Video2",
"url": "http://www.videourl3.com/"
},
{
"name": "Video2",
"url": "http://www.videourl3.com/"
}
]
}
]
}
编码为
// get all the categories from the database
$cats = get_categories();
header(\'Content-type: application/json\');
echo \'{
"categories": [\';
foreach ($cats as $cat) {
// setup the cateogory ID
$cat_id= $cat->term_id;
query_posts("cat=$cat_id&posts_per_page=9999");
echo \'
{
"cat_id": "\'.$cat_id.\'",\';
echo \'
"cat_name": "\'.$cat->name.\'",\';
echo \'
"posts": [\';
if (have_posts()) : while (have_posts()) : the_post();
if (get_post_meta($post->ID, \'apls_video_youtube\', true) != \'\'){
$url = \'http://www.youtube.com/watch?v=\';
$url .= get_post_meta($post->ID, \'apls_video_youtube\', true);
} else {
$url = get_post_meta($post->ID, \'apls_video_hosted\', true);
}
echo \'
{\';
echo \'
"name": "\'.get_the_title().\'", \';
echo \'
"url": "\'.$url.\'"\';
echo \'
},\';
endwhile; endif;
echo \'
]\';
echo \'
},\';
}
echo \'
]\';
echo \'
}\';
这对我来说很有效,但在每个循环的最后一项中都会遇到“,”的问题,所以JSON输出对事务长来说是无效的。我怎样才能修复它?