phparrayssortingmultidimensional-arraycustom-sort

Sort a 2d array to maintain originally grouped second-level keys, then custom sort by second level values


I want to sort two dimension array but its keys and its values. Array is like this

[
    ['Transport' => 'imagem3.png'],
    ['Transport' => 'imagem2.png'],
    ['Transport' => 'imagem1.png'],
    ['First' => 'dscn2439.jpg'],
    ['First' => 'dscn2454.jpg'],
    ['First' => '06052010282.jpg'],
    ['First' => 'dscn2357.jpg'],
    ['Manufacture' => '120140220_191807.jpg'],
    ['Manufacture' => '20140220_191429.jpg']
]

I have sorted array of array by its keys but what I want to do is I want to array like this

[
    ['Transport' => 'imagem1.png'],
    ['Transport' => 'imagem2.png'],
    ['Transport' => 'imagem3.png'],
    ['First' => 'dscn2439.jpg'],
    ['First' => 'dscn2454.jpg'],
    ['First' => 'dscn2357.jpg'],
    ['First' => '06052010282.jpg'],
    ['Manufacture' => '120140220_191807.jpg'],
    ['Manufacture' => '20140220_191429.jpg']
]

I have sorted by its keys I am not able to sort by value please help what I have to do

function getListPortfolio($params) {
    $dir = './images/portfolio/';
    // Open a directory, and read its contents
    $folderArray = array();
    $fileArray = array();
    $extArray = array('.jpg', '.jpeg', '.png', '.gif');
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($subdir = readdir($dh)) !== false) {
                if (is_dir($dir.$subdir)) {
                    if (!($subdir == '.' || $subdir == '..')) {
                         $folderArray[] = $subdir;
                    }
                }
            }
        
            arsort($folderArray);
            foreach ($folderArray as $key => $value) {
                if ($dhSub = opendir($dir . $value)) {
                    while (($files = readdir($dhSub)) !== false) {
                        $fileExists = $dir . $value . '/' . $files;
                        if (exif_imagetype($fileExists)) {
                            if (is_file($fileExists)) {
                                $fileArray[][$value] = $files;
                            }
                        }
                    }
                }
            }
            closedir($dh);
        }
    }
    return $fileArray;
}

Solution

  • So you want to sort your array by value. What don't you use usort like this:

    function cmp($a, $b)
    {
        if ($a == $b)
            return 0;
        return ($a < $b) ? -1 : 1;
    }
    
    usort($arr, 'cmp');
    
    print_r($arr);
    

    $arr being the array you want to sort.