PDA

View Full Version : مشکل در ترکیب ارایه ها



samiasoft
پنج شنبه 02 خرداد 1398, 21:18 عصر
سلام

دوستان فرض کنید ما 2 جدول post و comment داریم.

برای جدول post دستور زیر رو نوشتم :


$sql="SELECT * FROM `tbl_posts` ";
$result = $this->connect()->prepare($sql);
$result->execute();
$posts= $result->fetchAll(\PDO::FETCH_ASSOC);

حالا اگر این خروجی رو بصورت جیسون نمایش بدیم
خروجی زیر رو دارم :
http://s8.picofile.com/file/8361431142/post.jpg

همچنین اگر برای جدول comment هم همان دستور رو بنویسیم خروجی زیر رو داریم :
http://s8.picofile.com/file/8361431168/comment.jpg
حالا اگر بیام با کوئری زیر جداول رو بهم ارتباط بدم و در دستور بالا این کوئری رو بنویسم :

$sql="SELECT
tbl_posts.post_id , tbl_posts.post_name , tbl_posts.post_content ,
tbl_comments.comment_id ,tbl_comments.post_id_FK ,tbl_comments.username ,tbl_comments.comment_content
FROM tbl_posts
JOIN tbl_comments
ON tbl_comments.post_id_FK=tbl_posts.post_id";
خروجی زیر رو خواهیم داشت :
http://s9.picofile.com/file/8361431468/all1.jpg
حالا سوالم اینجاست که
به چه صورت خروجی را بصورت زیر داشته باشم :
http://s8.picofile.com/file/8361431484/all2.jpg

samiasoft
پنج شنبه 02 خرداد 1398, 23:12 عصر
اومدم بدین صورت نوشتم و به اون حالتی که میخواستم رسیدم :


$sql="SELECT post_id_FK FROM tbl_comments GROUP BY post_id_FK"; $result = $this->connect()->prepare($sql);
$result->execute();
$count = $result->rowCount();


$sql="SELECT * FROM tbl_posts";
$result = $this->connect()->prepare($sql);
$result->execute();
$posts= $result->fetchAll(\PDO::FETCH_ASSOC);



for($post_id=1; $post_id <= $count; $post_id++){


$sql="SELECT * FROM tbl_comments WHERE post_id_FK=? ";
$result = $this->connect()->prepare($sql);
$result->bindValue(1, $post_id);
$result->execute();

$posts[$post_id-1]['comment']= $result->fetchAll(\PDO::FETCH_ASSOC) ;
}

return $posts;

اما دراین حالت مجبورشدم با حلقه چندبار به دیتابیس وصل بشم تا به اون حالت اطلاعات استخراج شوند.
به نظرتون راه دیگری وجود نداشت ؟ خود sql کوئری نداشت که به اون صورت گروه بندی کنه ؟!

plague
جمعه 03 خرداد 1398, 09:40 صبح
همه پست و کامنت ها رو بخون یبار
بعد تو حلقه بزرا و به هم وصلشون کن نیاز نداری توی حلقه کوئری بنویسیی



$posts="SELECT * FROM tbl_posts";
$comments ="SELECT * FROM tbl_comments ";



foreach($posts as $k=>$post ){

$posts[$k]['comment'] = [];

foreach($comments as $comment )
{
if($comment['post_id_FK'] == $post['id'])
{
$posts[$k]['comment'][] = $comment ;
}
}

}