suresh suresh - 2 months ago 15
JSON Question

php create json multiple arrays

php create json multiple arrays. Following code with php i need output like that json .. so many array and object confusing me. we using wordpres

<?php
$categories = get_categories( array(
'orderby' => 'name',
'parent' => 0
));

foreach ( $categories as $category ) {
$category_id = $category->term_id;
$category_name = $category->name;
echo $category_name;
echo "<br>";

$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'category' => $category_id
);

$myposts = get_posts( $args );
foreach( $myposts as $post ){
$category_postname = $post->post_title;
echo $category_postname;
echo "<br>";
}
}
?>


Php output is"

Testcat1
pos1
post2
Testcat2
post3
post4
TestCat3
post5
post 6


I need create Json like this:

{
"data": [
{
"cat": "Testcat1",
"post": [
{
"name": "post1"
},
{
"name": "post2"
}
]
},
{
"cat": "Testcat2",
"post": [
{
"name": "post3"
},
{
"name": "post4"
}
]
},
{
"cat": "Testcat3",
"post": [
{
"name": "post5"
},
{
"name": "post6"
}
]
}
]
}


i need like this json output.

Answer

You should put everything in an array and the json_encode it. I commented out your echos, so you could use them if you need later.

<?php 
$categories = get_categories( array(
    'orderby' => 'name',
    'parent'  => 0
));

// init empty array with root "data"
$array = array( 'data' => array() );
// set counter to 0 for array later on
$n = 0;

foreach ( $categories as $category ) {
    $category_id =  $category->term_id;
    $category_name = $category->name;

    // store cat.name
    $array['data'][$n]['cat'] = $category_name;
    // echo  $category_name;
    // echo "<br>";

    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'category'  => $category_id
    );

    $myposts = get_posts( $args );
    // init posts counter
    $i = 0;
    foreach( $myposts as $post ){
        $category_postname = $post->post_title;
        $array['data'][$n]['post'][$i]['name'] = $category_postname;
        $array['data'][$n]['post'][$i]['id'] = $post->ID;
        // echo $category_postname;
        // echo "<br>";
        // increment post loop counter
        $i++;
    }

    // increment counter for array
    $n++;
}

echo json_encode( $array );
?>
Comments