1

我有一个 PHP 中的目录路径/文件列表,如下所示:

path1/path2/foo1_jpg
path1/foo2_png
path2/path3/bar_pdf
path2/
path1/

我想将这些转换为 javascript 对象。我想只是将“/”转换为句点,然后说类似的话:

<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>

我唯一的问题是文件名或目录是否以数字开头,即我不能说:files.001.foo = "bar";

我相信我需要重载点运算符来处理以数字开头的名称。这是最好的方法,还是有其他方法?

我实际上是在尝试将表单的 php 字符串解析"x1x2...xn/y1y2...yn/..."为嵌套的 javascript 对象,其中 x_i、y_i、z_i 等是“/”以外的字符x1x2x3...xn.y1y2...yn.z1z2z3...zn = {};。我想我在这里找到了一些解决方案,因为该用户还尝试基于分隔字符串(在他的情况下为“_”)动态添加 javascript 对象。

4

1 回答 1

3

Where do I start: Don't use new Array() to create a new array, just use the literal []. Google the reasons.

An array isn't the same as an object - it's an augmentation of Object. so it doesn't support the dot-notation as such. Also, your PHP code is off: the quoted $files['name'] is ambiguous (PHP doesn't know what to print out: the value of $file, followed by ['name'] as a simple string, or $file['name']. But more than that: it's not in php tags...

Here's one way to do what you want - but you shouldn't use it:

var files = {};//create object. properties can be numeric, too
<?php
    foreach ($dirlist as $key => $file)
    {//use $key for numeric index/properties
        echo 'files['.$key.'] = "'.$file['name'].'";';
        //or with double quotes:
        echo "files[$key] = '{$file['name']}';";//need the curly's for ambiguity, or rather avoid ambiguity
    }
?>

If you want the properties to have leading zeroes, then you can by either using str_pad or substr('000'.$key,-3);

Here's what I'd do:

var files = JSON.parse('<?= json_encode($dirlist); ?>');

That's it.

于 2013-01-15T17:30:56.133 回答