Как отсортировать список файлов по имени и записать их в формате JSON с помощью php?

1

Я пишу код для получения списка файлов с сервера и записываю их в файл 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..... then 20151211_Clip.7z, 98765Img.zip...

  • 2
    лучше, если вы разберете его в php, а затем сделаете его json ....
  • 0
    Любой способ, которым я использую эти методы, работает для меня. :) PHP: сортировка
Показать ещё 1 комментарий
Теги:

3 ответа

1
Лучший ответ

Я добавил только одну sort($files_array); строки 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

Сначала используйте "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);
0

Я нашел это:

https://linqjs.codeplex.com/

Если вы являетесь разработчиком.net, это отличная библиотека.

Надеюсь, это поможет.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню