Данные повторяются php

#php

#php

Вопрос:

Я получаю данные из php. Один запрос выбирает комментарии, а другой комментарий. У меня проблема в том, что данные из запроса ответов повторяются:

 Array ( [0] => Array ( [comment] => data3 ) 
        [1] => Array ( [comment] => data4 ) 
      )
Array ( [0] => Array ( [comment] => data3 ) 
        [1] => Array ( [comment] => data4 ) 
        [2] => Array ( [comment] => data2 ) 
        [3] => Array ( [comment] => data1 ) 
      )
  

Но я хочу получить такие данные:

 Array ( [0] => Array ( [comment] => data3 ) 
        [1] => Array ( [comment] => data4 ) 
        [2] => Array ( [comment] => data2 ) 
        [3] => Array ( [comment] => data1 ) 
      )
  

Помогите мне, пожалуйста! Я буду очень благодарен

 <?php
$sql = "select * from comments where post_id=:post_id order by id desc";
$data = $db->prepare($sql);
$data->execute(array(':post_id' => $post_id));
$comments = $data->fetchAll();

foreach ($comments as $row) {

    $sql = "select * from reply where post_id=? and comment_id=? order by id desc";
    $data = $db->prepare($sql);
    $data->execute([$row['post_id'], $row['id']]);
    $replies = $data->fetchAll();

    foreach ($replies as $key => $reply) {

        $commentReeply = $reply['comment'];

        $replyArray[] = [
            'comment' => $commentReeply,
            ];

    }

    print_r($replyArray);

}  

Ответ №1:

Если я правильно понимаю вашу проблему, это происходит из-за того, что вы не очищаете свой $replyArray in между обработкой комментариев. Таким образом, он продолжает добавлять все ответы из всех комментариев в один и тот же массив.

Итак, что происходит:

 $comments = $data->fetchAll();
foreach ($comments as $row) {
    // get replies
   foreach ($replies as $key => $reply) {
       // push replies in replyArray
       // ===== Here is the error =====
      $replyArray[] = [ 'comment' => $commentReeply ];
      }
 }
  

Например

 $comments = [1, 2, 3]

get replies for comment 1 ($replies = [A, B, C])
   push replies in $replyArray (=> [A, B, C] )

get replies for comment 2 ($replies = [D, E, F])
   push replies in $replyArray (=> [A, B, C, D, E, F] )

get replies for comment 3 ($replies = [G, H, I])
   push $replies in $replyArray (=> [A, B, C, D, E, F, G, H, I] )
  

То, что вы, вероятно, хотите, это:

  ...
$comments = $data->fetchAll();

 // create an array to store the replies per comment
$ALLReplys=[];
foreach ($comments as $row) {
    // reset the reply array for this comment
   $THISreplys=[];
    // get replies
   foreach ($replies as $key => $reply) {
       // push replies in reply array for this comment
      $THISreplys[] = [ 'comment' => $commentReeply ];
      }

    // store $THISreplys in $ALLreplys
   $ALLreplys[] = $THISreplys;
 }
  

Например

 $comments = [1, 2, 3]

reset $THISreply
get replies for comment 1 ($replies = [A, B, C] )
   push replies in $THISreply (=> [A, B, C] )
push $THISreply in $ALLreplys
    $ALLreplys[] = $THISreply (=> [
                                  [0] = > [A, B, C]
                                  ]

reset $THISreply
get replies for comment 2 ($replies => [D, E, F] )
   push replies in $THISreply (=> [D, E, F] )
push $THISreply in $ALLreplys
    $ALLreplys[] = $THISreply (=> [
                                  [0] = > [A, B, C]
                                  [1] = > [D, E, F]
                                  ]

reset $THISreply
get replies for comment 3
   push replies in $THISreply (=> [G, H, I] )
push $THISreply in $ALLreplys
    $ALLreplys[] = $THISreply (=> [
                                  [0] = > [A, B, C]
                                  [1] = > [D, E, F]
                                  [2] = > [G, H, I]
                                  ]