对象数组的临时排序

时间:2010-12-02 17:41:23

标签: php sorting

我目前正在根据一组自定义条件对对象数组进行排序。数据如下:

// Array to Sort
Object
    $key    = value1
Object
    $key    = value2
Object
    $key    = value3
Object
    $key    = value4

// Comparison Object
Sorter
    $data = array('value1', 'value2', 'value4', 'value3');

我正在尝试减少循环次数,并认为应该有更简单/更快的方法来执行此操作。我不想将自定义值添加到对象本身进行排序。这样做的基本思想是能够从以前的数据集中提取自定义排序,而不对对象本身做任何事情。

我试着查看array_intersects等的文档,但我找不到任何好方法来处理这个......

这是我目前的代码:

$children   = array(
    array('key' => 'value1'),
    array('key' => 'value2'),
    array('key' => 'value3'),
    array('key' => 'value4')
);

$comparison = array('value1', 'value2', 'value4', 'value3');
$sorter = array();

// loop 1 -- create a map           
foreach ($children as &$child) {
    $sorter[] = array(
        'sort'  => array_search($child['key'], $comparison, true),
        'child' => &$child
    );
}

// loop 2 -- sort based upon the sort key
usort($sorter, array($this, 'compare'));

// loop 3 (ugh -- I think this can be done in 2 loops)
$output = array();
foreach ($sorter as &$item) {
    $output[] = $item['child'];
}

// return
return $output;

// sort function
private function compare( Array $a, Array $b ) { 
    if(  $a['sort']  ==  $b['sort'] ) { return 0 ; } 
    return ($a['sort'] < $b['sort']) ? -1 : 1;
} 

1 个答案:

答案 0 :(得分:1)

这个怎么样?

$children   = array(
    array('key' => 'value1'),
    array('key' => 'value2'),
    array('key' => 'value3'),
    array('key' => 'value4')
);

// not all values from $children are in there
$comparison = array('value1', 'value4', 'value3');

$ukey = count($comparison);
$output = array();
foreach ($children as $child) {
    if (($key = array_search($child['key'], $comparison)) !== false) {
        $output[$key] = $child;
    } else {
         // if value is not in $comparison, push it at the end
        $output[$ukey++] = $child;
    }
}

ksort($output);
return $output;

这将返回:

Array
(
    [0] => Array 
        (
            [key] => value1
        )
    [1] => Array 
        (
            [key] => value4
        )
    [2] => Array 
        (
            [key] => value3
        )
    [3] => Array 
        (
            [key] => value2
        )
)