【问题标题】:Laravel posts of the user in one column, separated in rows and the user name in the first line in the same column用户的 Laravel 帖子在一列中,按行分隔,用户名在同一列的第一行
【发布时间】:2020-09-01 21:59:36
【问题描述】:

我有两张桌子

用户

  • 身份证
  • 姓名

帖子

  • 身份证
  • 姓名
  • user_id

所有帖子都应该在这些帖子的所有者用户的同一列中,但是 laravel 中的 foreach 只打印在行中,并且无法以这种方式思考任何方式。

代码是:

<?php 

$search = \App\Post::all()->groupBy('user_id');
$total_users = \App\User::count();
$total_posts = 0; 

?>

    <table>
     <tbody>

     @foreach($search as $user_id => $posts)
       @if ($loop->first)
         <tr>
       @endif
    
         <td>            
           {{ $posts[0]->user->name }}
           <?php $total_posts += $posts->count();  ?>
         </td>
    
      @if ($loop->last)
        </tr>
      @endif

    @endforeach

    @for($c = 0; $c < floor($total_posts/$total_users); $c++)

     <?php
        $users_done = 0;
        $tr_done = false;
     ?>

    @foreach($search as $user_id => $posts)

      @if(isset($posts[$c]))
            
         @if ($loop->first)
            <tr>
         @endif
            
         <td>{{ $posts[$c]->name }}</td>                
                
         <?php
           $users_done++;
           $g++;
         ?>

         @if ($loop->last)
           <?php
              $tr_done = true;
           ?>               
           </tr>
         @endif
            
        @endif

     @endforeach  

     @if(!$tr_done)
        </tr>
     @endif

     @if($user_done>0 && $users_done<$total_users)
        
       @for($c = 0; $c < $total_users-$users_done; $c++)
          <tr><td></td></tr>
       @endfor
     @endif

     @endfor

    </tbody>
   </table>

我有 2k 个帖子行,我无法以这种方式打印!

请帮忙!!!

【问题讨论】:

    标签: laravel foreach


    【解决方案1】:

    你可以试试这样建表吗?

    $table = [];
    $users = 0;
    $posts = 0;
    
    foreach($users as $user){
        foreach($user->posts){
            $table[$posts][$users] = $post->name;
            $posts++;
        }
        $users++;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 2021-03-03
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      相关资源
      最近更新 更多