Skip to content
Advertisement

how to give name to sub array in php

I have got the final array with blog detail and related multiple comments for blog

$prev_blog = 0;

$finalArray = array();
foreach ($blog_details as $student)
{
    if ($prev_blog != $student->id)
    {
        $finalArray['blog'][] = array('bid' => $student->id,
            'blogTitle' => $student->blog_title,
            'blogImage' => $student->blog_image,
            'blogDescription' => $student->blog_description
        );
        $prev_blog = $student->id;
    }
    $finalArray[key($finalArray)][] = array('comment ' => $student->comments);
}
$comm=json_encode($finalArray);
print_r($comm);

The result of the above code is as follow

{
    "blog":[
        {
            "bid":4,
            "blogTitle":"testing for slug",
            "blogImage":"1573222996.jpg",
            "blogDescription":"testing for blog slug.for saving blog slug"
        },
        {
            "comment ":"This is very nice blog "
        },
        {
            "comment ":"need to add some more comments "
        },
        {
            "comment ":"Nicely explained "
        },
        {
            "comment ":"Thanks for such a nice blog it is helpful "
        }
    ]
}

But the expected result should look like the following, Comments and blog details should be in the same array

{
    "blogDetail":[
        {
            "blogID":4,
            "blogChildGenre":"laravel",
            "blogTitle":"laravel 5.6 tutorial",
            "blogImage":"laravel.jpg",
            "blogDescription":"This blog gives basic info about laravel",
            "comments":[
                {
                    "comment":"This is first comment",

                },
                {
                    "comment":"This is first comment",

                },
                {
                    "comment":"This is first comment",

                }
            ]
        }
    ]
}

Is there a way to give a name for a comment?

Advertisement

Answer

Try this

$finalArray = array();
foreach ($blog_details as $student)
{
    if (!isset($finalArray[$student->id]))
    {
        $finalArray[$student->id] = [
            'blogDetail' => []
        ];
    }

    if(empty($finalArray[$student->id]['blogDetail'])) {
        $finalArray[$student->id]['details'] = [
            'bid' => $student->id,
            'blogTitle' => $student->blog_title,
            'blogImage' => $student->blog_image,
            'blogDescription' => $student->blog_description,
            'comments' => []
        ]
    }

    $finalArray[$student->id]['blogDetail']['comments'][] = [
        'comment' => $student->comments
    ];

}
$comm=json_encode($finalArray);

print_r($comm);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement