Get List of Directories in AWS S3 as array keys. Nested subfolders
<?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() ); |
This comment has been minimized.
This comment has been minimized.
<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
This comment has been minimized.
I use this jQuery to create unordered list elements, nested for subfolders