我编写了从服务器获取文件列表的代码,并将它们写入JSON文件,但每次自动更改时都会出现问题。 我的代码是
<?php
$dir = "office/";
if(is_dir($dir)){
if($dh = opendir($dir)){
while(($file = readdir($dh)) != false){
if($file != "." and $file != ".."){
$files_array[] = array('file' => $file); // Add the file to the array
}
}
}
$return_array =array('dir' => $files_array);
exit (json_encode($return_array));
}
?>
,输出
{
"dir": [
{
"file": "FreeWallApp.zip"
},{
"file": "20151211_Clip.7z"
},{
"file": "QRite.7z"
},{
"file": "CustomDialog_app.zip"
},{
"file": "LockScreenBasicApp.apk"
},{
"file": "ImgViewEffects.zip"
},{
"file": "98765Img.zip"
},
]
}
我的问题是如何排序这样的名称列表,如第一个 a b c .....然后1 2 3
{
"dir": [
{
"file": "CustomDialog_app.zip"
},{
"file": "FreeWallApp.zip"
},{
"file": "LockScreenBasicApp.apk"
},{
"file": "QRite.7z"
},{
"file": "20151211_Clip.7z"
},{
"file": "98765Img.zip"
},
]
}
我需要输出上面的输出,即CustomDialog_app.zip
,FreeWallApp.zip
.....然后20151211_Clip.7z
,98765Img.zip
......
答案 0 :(得分:1)
我只添加了一行sort($files_array);
它的工作正常......
<?php
$dir = ".";
if(is_dir($dir)){
if($dh = opendir($dir)){
while(($file = readdir($dh)) != false){
if($file != "." and $file != ".." and $file!="index.php"){
$files_array[] = array('file' => $file); // Add the file to the array
}
}
// this line make my problem solved
sort($files_array);
}
$return_array =array('dir' => $files_array);
exit (json_encode($return_array));
}
?>
答案 1 :(得分:1)
首先使用"sort"
来排序数组的自然短路。然后使用下面的自定义代码:
$abcd[0]["file"] = "FreeWallApp.zip";
$abcd[1]["file"] = "CustomDialog_app.zip";
$abcd[2]["file"] = "20151211_Clip.7z";
$abcd[3]["file"] = "QRite.7z";
$abcd[4]["file"] = "LockScreenBasicApp.apk";
$abcd[5]["file"] = "ImgViewEffects.zip";
$abcd[6]["file"] = "98765Img.zip";
sort($abcd);
$array1 = array();
$array2 = array();
foreach($abcd as $bb){
if(is_numeric(substr(array_values(explode(".",$bb['file']))[0] , 0,1 ) )) {
$array1[]["file"] = $bb['file'] ;
}else{
$array2[]["file"] = $bb['file'] ;
}
}
$abcd = array_merge ($array2,$array1) ;
echo json_encode($abcd);
答案 2 :(得分:0)