5

Update: I've changed the code as following

$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));

Output is:

{
    "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......"
                    }
                ]
            }
        },
        {......

The issue is:

Only one post is being displayed Same post is being displayed in each category A 0(zero) was added

So I need your suggestion to fix the issue.

==========================Previous Part=========================

I want to get json output as

 {
    "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/"
                }
            ]
        }
    ]
}

So coded as

// 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 '
}';

This worked for me but facing issue with "," at the last item of every loop, so JSON output is being invalid to purser. How can I fix it?

2
  • What version of PHP are you using?
    – totels
    Nov 13, 2012 at 16:21
  • PHP version 5.3
    – PHPLearner
    Nov 13, 2012 at 16:23

1 Answer 1

9

If you are using PHP 5.2+ you're best bet is to just make a PHP array or object and use json_encode().

UPDATED:

$cats = get_categories();
$output = array('categories' => array());

foreach ($cats as $cat) {
    $cat_output = array(
        'cat_id' => $cat->term_id,
        'cat_name' => $cat->name,
        'posts' => array(),
    );

    // should be able to use -1 to get all posts, rather than 9999
    $args = array('numberposts=' => -1, 'category' => $cat->cat_ID);
    $myposts = get_posts($args);

    foreach( $myposts as $post ) {
        if ($youtube_id = get_post_meta($post->ID, 'apls_video_youtube', TRUE)) {
            $url = "http://www.youtube.com/watch?v={$youtube_id}";
        } else {
            $url = get_post_meta($post->ID, 'apls_video_hosted', TRUE);
        }

        $cat_output['posts'][] = array(
            'name' => get_the_title($post->ID),
            'url' => $url,
        );
    }

    $output['categories'][] = $cat_output;
}

header("Content-type: application/json");
die(json_encode($output));
6
  • 5
    Also, you probably don't want to use query_posts in this context, get_posts will probably serve you better.
    – totels
    Nov 13, 2012 at 16:34
  • The actual difficulty I'm facing is: I cannot use loop inside another loop. You did the most of the part. I need a bit help to set loop get post name and url. :(
    – PHPLearner
    Nov 13, 2012 at 17:04
  • As I said in my previous comment, use get_posts() instead of query_posts, it returns an array of posts you can use in a nested loop w/o any problem.
    – totels
    Nov 13, 2012 at 17:19
  • I've added more detail in question after trying your instruction. Please check and instruct me if possible.
    – PHPLearner
    Nov 13, 2012 at 17:51
  • 2
    New code posted, try that.
    – totels
    Nov 13, 2012 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.