简体   繁体   English

创建由数组组成的json对象

[英]Creating json objects that consit of arrays

In laravel I am getting list of articles from my query and later I am getting foreach of these articles number of comments and paths for all of their image files and videos. 在laravel中,我从查询中获取了文章列表,后来,我又获取了这些文章中的所有图像文件和视频的注释和路径。 My goal is to make an array of json objects that would look like this: 我的目标是制作一个看起来像这样的json对象数组:

[{
   id: id,
   title: title,
   summary: summary,
   comments: 'commentsCount',
   images: {
      path: 'path',
      path: 'path',
      path: 'path',
    }
 },
...
]

Not sure how to combine and make that kind of an array, this is my failed attempt: 不知道如何组合和制作这种数组,这是我失败的尝试:

$result = Article::where('publish', 1)->orderBy('created_at', 'desc')->paginate(15);
    $articles = [];

    foreach($result as $article){
      $articles[] = $article;
      $articles[]['comments'] = $article->comments()->count();

      foreach ($article->medias as $media){
        $articles[]['comments']['images'] = $media->path;
      }
    }

Updated code: 更新的代码:

This is was the simplest solution that gave me wanted result: 这是给我想要的结果的最简单的解决方案:

$result = Article::where('publish', 1)->orderBy('created_at', 'desc')->paginate(15);

    foreach($result as $article){
      $articles[$article->id] = $article;
      $articles[$article->id]['comments'] = $article->comments()->count();
      $articles[$article->id]['medias'] = $article->medias()->get();
    }

    return $articles;

I suspect your problem is the way you use [] : 我怀疑您的问题是您使用[]

foreach($result as $article){
  $articles[] = $article;
  $articles[]['comments'] = $article->comments()->count();

  foreach ($article->medias as $media){
    $articles[]['comments']['images'] = $media->path;
  }
}

Every time you write $articles[] ... = ... you append a brand new element to the end of the array. 每次编写$articles[] ... = ...时,都会在数组末尾附加一个全新的元素。

If you want to append one element and then append subelements you need a different approach: 如果要附加一个元素然后附加子元素,则需要另一种方法:

  1. Specify an index inside the brackets (which you can be a variable). 在方括号内指定一个索引(您可以将其作为变量)。

  2. Compose the element first into a temporary variable, append it once at the end of the loop iteration. 首先将元素组成一个临时变量,然后在循环迭代结束时将其追加一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM