Advertisement
matthewpoer

Mashedup Array Sorting

Feb 21st, 2014
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. $table1_result = array(
  3.   0 => array('score' => 110, array('node_id'=>1, 'name'=>'apple')),
  4.   1 => array('score' => 89, array('node_id'=>2, 'name'=>'orange')),
  5.   3 => array('score' => 110, array('node_id'=>3, 'name'=>'something')),
  6. );
  7.  
  8. $table2_result = array(
  9.   0 => array('score' => 90, 'value' => 'banana'),
  10.   1 => array('score' => 59, 'value' => 'grapes'),
  11. );
  12.  
  13. $combined = array_merge($table1_result,$table2_result);
  14.  
  15. foreach($combined as $key => $row){
  16.   $result_one[$key] = $row['score'];
  17.   if(isset($row['value'])){
  18.     $result_two[$key] = $row['value'];
  19.   }else{
  20.     $result_two[$key] = $row['0'];
  21.   }
  22. }
  23.  
  24. array_multisort($result_one, SORT_DESC, $result_two, SORT_ASC, $combined);
  25.  
  26. var_dump($combined);
  27.  
  28. //result you wanted
  29.  
  30. array(
  31.   110 => array('node_id'=>1, 'name'=>'apple'),
  32.   110 => array('node_id'=>3, 'name'=>'something'),
  33.   90 => 'banana',
  34.   89  => array('node_id'=>2, 'name'=>'orange'
  35.   59 => 'grapes'
  36. )
  37.  
  38. // result this provides
  39.  
  40. array(5) {
  41.   [0] =>
  42.   array(2) {
  43.     'score' =>
  44.     int(110)
  45.     [0] =>
  46.     array(2) {
  47.       'node_id' =>
  48.       int(1)
  49.       'name' =>
  50.       string(5) "apple"
  51.     }
  52.   }
  53.   [1] =>
  54.   array(2) {
  55.     'score' =>
  56.     int(110)
  57.     [0] =>
  58.     array(2) {
  59.       'node_id' =>
  60.       int(3)
  61.       'name' =>
  62.       string(9) "something"
  63.     }
  64.   }
  65.   [2] =>
  66.   array(2) {
  67.     'score' =>
  68.     int(90)
  69.     'value' =>
  70.     string(6) "banana"
  71.   }
  72.   [3] =>
  73.   array(2) {
  74.     'score' =>
  75.     int(89)
  76.     [0] =>
  77.     array(2) {
  78.       'node_id' =>
  79.       int(2)
  80.       'name' =>
  81.       string(6) "orange"
  82.     }
  83.   }
  84.   [4] =>
  85.   array(2) {
  86.     'score' =>
  87.     int(59)
  88.     'value' =>
  89.     string(6) "grapes"
  90.   }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement