Home:ALL Converter>Temporary sorting of an Object Array

Temporary sorting of an Object Array

Ask Time:2010-12-03T01:41:22         Author:ansiart

Json Formatter

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'], $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;
} 

Author:ansiart,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/4338027/temporary-sorting-of-an-object-array
yy