php - Temporary sorting of an Object Array -


i'm sorting array of objects based on custom set of criteria. data looks like:

// array 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 reduce number of loops, , figured there should easier/faster way this. not want add custom values objects sort. basic idea of able extract custom sort previous data set, without doing objects themselves.

i tried looking documentation of array_intersects, etc, couldn't find method handle ....

here's code 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 map            foreach ($children &$child) {     $sorter[] = array(         'sort'  => array_search($child['key'], $comparison, true),         'child' => &$child     ); }  // loop 2 -- sort based upon sort key usort($sorter, array($this, 'compare'));  // loop 3 (ugh -- think can done in 2 loops) $output = array(); foreach ($sorter &$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 this?

$children   = array(     array('key' => 'value1'),     array('key' => 'value2'),     array('key' => 'value3'),     array('key' => 'value4') );  // not values $children in there $comparison = array('value1', 'value4', 'value3');  $ukey = count($comparison); $output = array(); foreach ($children $child) {     if (($key = array_search($child['key'], $comparison)) !== false) {         $output[$key] = $child;     } else {          // if value not in $comparison, push @ end         $output[$ukey++] = $child;     } }  ksort($output); return $output; 

this return:

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

Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -