I have a list of directory paths/files in PHP, like so:
path1/path2/foo1_jpg
path1/foo2_png
path2/path3/bar_pdf
path2/
path1/
and I want to convert these to javascript objects. I thought about just converting the "/" to periods and then saying something like:
<script>
var files = new Array();
<?php $dirlist = getFileList("images",true); ?> //returns array of directory paths (and other info)
<?php foreach($dirlist as $file): ?>
files.<?=$file['name']?> = "$file['name']";
//where $file['name'] returns, for example, path1.path2.foo1_jpg
<?php endforeach; ?>
console.log(files);
</script>
The ONLY issue I have is if a file name or directory begins with a number, i.e. I can't say: files.001.foo = "bar";
I believe that I need to overload the dot operator to handle names beginning with numbers. Is that the best way, or is there another way?
I'm essentially trying to parse a php string of the form "x1x2...xn/y1y2...yn/..."
, where x_i,y_i,z_i,etc are characters other than "/", into a nested javascript object x1x2x3...xn.y1y2...yn.z1z2z3...zn = {};
. I think I found something of a solution here Since this user was also trying to dynamically add javascript objects based on a delimited string (in his case a "_").