2015-09-16 57 views
2

我有這樣一個數組:在PHP中排序和重構多維數組?

$toSort = array(
    1 => 
     [ 
      'value' => 8000, 
      'key' => 1007 
     ], 
    2 => 
     [ 
      'value' => 8001, 
      'key' => 1007 
     ], 
    3 => 
     [ 
      'value' => 8002, 
      'key' => 1013 
     ], 
); 

我想排序和重組這樣的:

$toSort = array(
    1007 => 
     [ 
      [0] => 8000, 
      [1] => 8001 
     ], 
    1013 => 
     [ 
      [0] => 8002 
     ] 
); 

應該針對不同項目的隨機工作量(不同勢鍵/值) 。

+0

這不是排序。只需循環輸入數組,然後用相同的鍵將值推送到輸出數組的元素。 – Barmar

+0

排序是指根據排序條件重新排列數組的元素,而不是重新排列數組的結構。 – Barmar

回答

0

這樣的事情呢?

//A new array to move the data to. 
var $result = array(); 

//Loop through the original array, and put all the data 
//into result with the correct structure. 
foreach($toSort as $e) { 
    //If this key is not set yet, then create an empty array for it. 
    if(!isset($result[$e['key']])) $result[$e['key']] = array() 
    //Add the value to the end of the array. 
    $result[$e['key']][] = $e['value']; 
} 

//Sort the result, based on the key and not the value. 
//If you want it to be based on value, just use sort() instead. 
ksort($result) 

//If you want the sub-arrays sorted as well, loop through the array and sort them. 
foreach($result as $e) 
    sort($e); 

Disclaimar:我還沒有測試過這段代碼。

+0

嘿謝謝:)它的作品:D – Ulfe

0
$a=array(
    1 => 
     [ 
      'value' => 8000, 
      'key' => 1007 
     ], 
    2 => 
     [ 
      'value' => 8001, 
      'key' => 1007 
     ], 
    3 => 
     [ 
      'value' => 8002, 
      'key' => 1013 
     ], 
); 

$a=call_user_func(function($a){ 
    $ret=array(); 

    foreach($a as $v){ 
    if(array_key_exists($v['key'],$ret)){ 
     $ret[$v['key']][]=$v['value']; 
     } else { 
     $ret[$v['key']]=array($v['value']); 
     } 
     } 
     return $ret; 
},$a); 
var_dump($a);