Files array inside json array

I’m generating json of my page to parse selections of it into a div when an element is clicked.

I’m stuck (and possibly doing this completely wrong) at generating a nested array which contains details for all the files associated with each page.

From looking around I’ve found that you can’t put foreach loops inside arrays in PHP but I figured someone here might have an idea because this seems like it would be a normal usecase?

foreach($data as $response) {
  $json[] = [
    'title' => (string)$response->title(),
    'name' => (string)$response->name(),
    'caption' => (string)$response->caption(),
    foreach ($response->files() as $file) {
      'files' => [
        'file' => (string)$file->url(),
        'type' => (string)$file->type(),
      ];
    }
  ];
}

Indeed you cannot use a loop inside an array. You have to move the second foreach up, generate the files array, then the $json array and pass $files as value:

foreach($data as $response)
    foreach ($response->files() as $file) {
        $files[] = [
            'file' => (string)$file->url(),
            'type' => (string)$file->type(),
        ];
    }
  $json[] = [
    'title'   => (string)$response->title(),
    'name'    => (string)$response->name(),
    'caption' => (string)$response->caption(),
    'files'   => $files,
  ];
}

ahh amazing, yep that did it!
thanks so much for that :+1:

the only change I had to make was declare the $files variable inside the foreach. originally it was outside along with the $json variable and it was generating a strange recursive output where each $files array would include the files of all the previous pages before it.

this worked if anyone comes across a similar problem :slightly_smiling_face:

$json = [];

foreach($data as $response) {
  $files = [];

  foreach ($response->files() as $file) {
    $files[] = [
      'file' => (string)$file->url(),
      'type' => (string)$file->type(),
    ];
  }

  $json[] = [
    'title'   => (string)$response->title(),
    'name'    => (string)$response->name(),
    'caption' => (string)$response->caption(),
    'files'   => $files,
  ];
}