[英]How to get a list of files of subfolders and write them in a JSON using php?
[英]How to sort the list of files name and write them in a JSON using php?
我編寫了用於從服務器獲取文件列表的代碼,並將它們寫入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"
},
]
}
在這里,我的問題是, 如何對這樣的名稱列表進行排序 ,例如第一個abc .....然后是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
...
我只添加了一行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));
}
?>
首先使用"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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.