如何在php中命名子数组
我已经得到了博客详细信息和博客相关的多个评论的最终数组如何在php中命名子数组,php,arrays,json,multidimensional-array,Php,Arrays,Json,Multidimensional Array,我已经得到了博客详细信息和博客相关的多个评论的最终数组 $prev_blog = 0; $finalArray = array(); foreach ($blog_details as $student) { if ($prev_blog != $student->id) { $finalArray['blog'][] = array('bid' => $student->id, 'blogTitle' => $s
$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);
上述代码的结果如下所示
{
"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 "
}
]
}
但是预期的结果应该如下所示,评论和博客细节应该在同一个数组中
{
"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",
}
]
}
]
}
有没有办法给评论起个名字?试试这个
$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);
只需稍作改动,我就得到了准确的输出…谢谢Vinay,改动是什么?