开发者

Temporary sorting of an Object Array

I'm currently sorting an array of objects based on a custom set of criteria. The data looks like:

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

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

I'm trying to reduce the number of loops, and figured there should be an easier/faster way to do this. I DO NOT want to add custom values to the objects themselves to sort. The basic idea of this is to be able to extract a custom sort from a previous data set, without doing anything to the objects themselves.

I tried looking into the documentation of array_intersects, etc, but I couldn't find any good method to handle this ....

Here's the code I have currently:

$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'], $compa开发者_Go百科rison, 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;
} 


How about this?

$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;

This would return:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜