【问题标题】:In laravel,how can I use foreach loop?在 laravel 中,如何使用 foreach 循环?
【发布时间】:2018-05-15 15:40:00
【问题描述】:

当我使用这段代码时:

Route::get('/user/{id}/posts', function ($id){
   $post = User::find($id)->postst;
   return $post;
});

输出是:

[
    {
        "id":1,
        "user_id":1,
        "title":"Eloquent Basic Insert",
        "content":"By eloquent we can easily insert a data and it is awesome",
        "created_at":"2018-05-15 14:45:34",
        "updated_at":"2018-05-15 14:45:34",
        "deleted_at":null
    },
    {
        "id":2,
        "user_id":1,
        "title":"Add with create",
        "content":"This might be fail",
        "created_at":"2018-05-15 14:47:59",
        "updated_at":"2018-05-15 14:47:59",
        "deleted_at":null
    }
]

但是当我使用 foreach 循环时,它只显示一个数组

 Route::get('/user/{id}/posts', function ($id){
   $post = User::find($id)->postst;
   foreach ($post as $post){
       return $post->title. '<br>';
   }
});

这段代码的输出是:

Eloquent 基本插入

如何在浏览器上显示数组的所有标题?我的代码有什么问题?

【问题讨论】:

  • return 被放置在你的 for 循环中。
  • 谢谢...echo解决了这个问题

标签: php laravel foreach


【解决方案1】:

您正在做的是在第一个循环中返回标题。 你需要把你的return 放到你的foreach 之外:

Route::get('/user/{id}/posts', function ($id){
   $post = User::find($id)->postst;
   $titles = "";
   foreach ($post as $post){
       $titles .= $post->title. '<br>';
   }
   return $titles;
});

【讨论】:

    【解决方案2】:

    只需用 echo 替换返回词就可以了

     Route::get('/user/{id}/posts', function ($id){
     $post = User::find($id)->postst;
      foreach ($post as $post){
       echo $post->title. '<br>';
      }
    });
    

    【讨论】:

      【解决方案3】:

      只是为了不同的东西,你应该能够做这样的事情:

      Route::get('/user/{id}/posts', function ($id){
          $posts = User::with('posts')->find($id)->posts;
          return $posts->pluck('title');
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-27
        • 2022-12-20
        • 2020-07-09
        • 2016-09-08
        • 1970-01-01
        • 1970-01-01
        • 2020-06-17
        相关资源
        最近更新 更多