PHP按特定顺序数组排序2d字符串数组

时间:2015-04-07 15:06:43

标签: php arrays sorting multidimensional-array

我是php的新手,并且一直在尝试使用特定的顺序数组对2d字符串数组进行排序。一直在使用'usort'和'comparison',但在使用2d数组和字符串时似乎无法绕过它们。

需要将数组输入到方法并返回已排序的数组,格式相同。因此,对于数组中的每个条目,它将根据顺序数组的顺序对第二级“文件”值进行排序。有任何建议如何实现这一目标?

//actual array to be sorted by 'file'
$Array ( 
[0] => Array ( [source] => img/table/icon/toxic.svg [file] => toxic ) 
[1] => Array ( [source] => img/table/icon/health.svg [file] => health ) 
[2] => Array ( [source] => img/table/icon/irritant.svg [file] => irritant   ));

//order array with desired sort order
$order = array("irritant","corrosive","environment" ,"health","toxic","oxidizing","flammable","explosive","gas");

//Desired Output Result
$Array ( 
[0] => Array ( [source] => img/table/icon/irritant.svg [file] => irritant )
[1] => Array ( [source] => img/table/icon/health.svg [file] => health ) 
[2] => Array ( [source] => img/table/icon/toxic.svg [file] => toxic ) );

首先看到的是刺激性,最后是有毒的。)

2 个答案:

答案 0 :(得分:1)

这可以通过巧妙地使用PHP的usort函数来实现。您的电话可能如下所示:

$order = array("irritant","corrosive","environment" ,"health","toxic","oxidizing","flammable","explosive","gas");
usort($array, function ($a, $b) use ($order) {
    $aOrder = array_search($a['file'], $order);
    $bOrder = array_search($b['file'], $order);
    if ($aOrder == $bOrder) return 0;
    return ($aOrder > $bOrder) ? 1 : -1;
});

答案 1 :(得分:0)

基本方法是遍历数组和顺序数组,并将键重新分配到新数组中......

<?php
    $a[] = array('source' => 'img/table/icon/toxic.svg','file'=>'toxic');
    $a[] = array('source' => 'img/table/icon/health.svg','file'=>'health');
    $a[] = array('source' => 'img/table/icon/irritant.svg','file'=>'irritant');

    $b = array();

    $order = array("irritant","corrosive","environment","health","toxic","oxidizing","flammable","explosive","gas");

    foreach ($a as $arr) {
        foreach ($order as $key => $o) {
            if ($o == $arr['file']) {
                $b[$key] = $arr;
                break;
            }
        }
    }
    ksort($b);
    print_r(array_values($b)); // or print_r($b); if you dont want sequential keys
?>

输出:

Array ( 
[0] => Array ( [source] => img/table/icon/irritant.svg [file] => irritant ) 
[1] => Array ( [source] => img/table/icon/health.svg [file] => health ) 
[2] => Array ( [source] => img/table/icon/toxic.svg [file] => toxic )
)