search

Home  >  Q&A  >  body text

Merge arrays created using Google Drive NextPageToken into one array

<p>I have the following code for downloading files from Google Drive, the number of files is determined by nextPageToken as shown below. </p> <p>The code will continue adding arrays to the $files array until nextPageToken is null. At this point, I have an unknown number of sub-arrays and I wish to merge them into a single array without looping through all returned arrays - is there an easy way to achieve this using PHP? </p> <p>So, in the code below, I want $files[] to be a single array. For example: </p> <p><code>$result = array_merge($files); </code>will only produce the same result</p> <pre class="brush:php;toolbar:false;">``` $nextPageToken = "empty" ; while ( $nextPageToken != null) { $responseFiles = $drive->ListFiles( $optParams); $nextPageToken = $responseFiles->getNextPageToken(); $files[] = $responseFiles->getFiles(); $optParams = array( 'fields' => "nextPageToken, files(contentHints/thumbnail,fileExtension,iconLink,id,name,size,thumbnailLink,webContentLink,webView Link,mimeType,parents)", 'q' => "'".$match[0]."' in parents", 'pageToken' => $nextPageToken, 'orderBy' => 'modifiedTime desc, name' ); } ```</pre></p>
P粉872101673P粉872101673467 days ago551

reply all(1)I'll reply

  • P粉805931281

    P粉8059312812023-08-14 16:48:10

    Create an empty $files array before the loop, then merge and return in each loop like below.

    $files = [];
    $nextPageToken = "empty";
    
    $optParams = array(
        'fields' => "nextPageToken, files(contentHints/thumbnail,fileExtension,iconLink,id,name,size,thumbnailLink,webContentLink,webView Link,mimeType,parents)",
        'pageToken' => $nextPageToken,
        'orderBy' => 'modifiedTime desc, name'
    );
    
    while ( $nextPageToken != null) {
      $responseFiles = $drive->ListFiles($optParams);
      $nextPageToken = $responseFiles->getNextPageToken();
      $files = array_merge($files, $responseFiles->getFiles());
      $optParams['q'] => "'".$match[0]."' in parents";
    }
    

    See array_merge’s API documentation for more information.

    reply
    0
  • Cancelreply