Last active
October 2, 2018 18:14
-
-
Save donjajo/bac592fbf63c0c4a4c1ca9462efe5dbc to your computer and use it in GitHub Desktop.
Get List of Directories in AWS S3 as array keys. Nested subfolders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once( __DIR__ . '/aws/aws-autoloader.php' ); | |
use Aws\S3\S3Client; | |
define( 'AWS_S3', [ | |
'key' => '', | |
'secret' => '', | |
'bucket' => '' | |
]); | |
function get_dirs() { | |
$s3 = S3Client::factory([ | |
'credentials' => [ | |
'key' => AWS_S3[ 'key' ], | |
'secret' => AWS_S3[ 'secret' ], | |
], | |
'region' => 'us-east-1', | |
'version' => 'latest' | |
]); | |
$objects = $s3->getIterator( 'ListObjects', [ 'Bucket' => AWS_S3[ 'bucket' ] ] ); | |
$dirs = []; | |
foreach( $objects as $ob ) { | |
if( preg_match( '/^.*\/$/', $ob[ 'Key' ] ) ) { | |
$split = explode( '/', $ob[ 'Key' ] ); | |
$dirs = nest_dir( $dirs, $split ); | |
} | |
} | |
return $dirs; | |
} | |
function nest_dir( $ref, $dirs ) { | |
$dirs = array_filter( $dirs ); | |
foreach( $dirs as $index => $dir ) { | |
$parent = @$dirs[ $index - 1 ]; | |
if( $parent && isset( $ref[ $parent ] ) ) { | |
$ref[ $parent ][ $dir ] = nest_dir( [], array_slice( $dirs, $index + 1 ) ); | |
continue; | |
} | |
if( !$parent || ( $parent && array_search( $parent, $dirs ) === 0 ) ) | |
$ref[ $dir ] = []; | |
} | |
return $ref; | |
} | |
print_r( get_dirs() ); |
<ul id="dirs"></ul>
show_dirs( $( '#dirs' ), json_object, '' )
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use this jQuery to create unordered list elements, nested for subfolders