2015-06-05 37 views
4

爲了我有一個數組:移動特定的陣列項目陣列的開頭沒有改變其餘

Array 
(
    [product1] => Array 
    (
     [id] => 1 
     [title] => 'p1' 
     [extra] => Array(
      [date] => '1990-02-04 16:40:26' 
     ) 
    ) 

    [product2] => Array 
    (
     [id] => 2 
     [title] => 'p2' 
     [extra] => Array(
      [date] => '1980-01-04 16:40:26' 
     ) 
    ) 
    [product3] => Array 
    (
     [id] => 3 
     [title] => 'p3' 
     [extra] => Array(
      [date] => '2000-01-04 16:40:26' 
     ) 
    ) 
    [product4] => Array 
    (
     [id] => 4 
     [title] => 'p4' 
     [extra] => Array(
      [date] => '1995-01-04 16:40:26' 
     ) 
    ) 
    [product5] => Array 
    (
     [id] => 5 
     [title] => 'p5' 
     [extra] => Array(
      [date] => '1960-01-04 16:40:26' 
     ) 
    ) 
    ... 

我需要2種產品與最新的日期,並將其移動到數組的開始。

我已經看過multisort函數,並且我可以像這樣對數組進行排序,但隨後整個數組將按日期排列,我想維護數組的順序,但只是碰到最新的2行。

我需要從數組中選出2個最新的(按日期排序),然後將它們移到數組的開頭。因此,IDS的順序應該是:

3,4,1,2,5 

最新2已經被移動到陣列的前端,其餘仍然由ID排序。

+0

您可以發佈預期的輸出 –

+0

使用array_shift() –

+0

您能否提供一些關於您想要實現的更多信息? –

回答

0
// Making array with only dates 
$dates = array(); 
foreach ($arr as $key => $item) 
    $dates[$key] = $item['extra']['date']; 
// Sort it by date saving keys 
uasort($dates, function($i1, $i2) { return strtotime($i1) - strtotime($i2); }); 
// Take keys 
$dates = array_keys($dates); 
// Create array with two needed items 
$newarray = array($dates[0] => $arr[$dates[0]], $dates[1] => $arr[$dates[1]]); 
// remove these items 
unset($arr[$dates[0]]); unset($arr[$dates[1]]); 
// put them in array start 
$arr = array_merge($newarray, $arr); 
var_dump($arr);  
0
// copy current array for new array 
$temp = $input; 

// sort temp array by latest date 
uasort($temp, function($a,$b) { 
    return (strtotime($a['extra']['date']) < strtotime($b['extra']['date'])); 
}); 

// for 2 key value pairs to get on top 
$sorted_keys = array_keys($temp); 

// initialize your required array 
$final = []; 

// two keys to move on top 
$final [ $sorted_keys[0] ] = $temp [ $sorted_keys[0] ]; 
$final [ $sorted_keys[1] ] = $temp [ $sorted_keys[1] ]; 

foreach ($input as $k => $v) 
{ 
    // insert your other array values except two latest 
    if(!array_key_exists($k, $final)) 
    { 
     $final[$k]=$v; 
    } 
} 

unset($temp); // free up resource 

$final是您所需的陣列

1

不是最優化的實現,但最直接的:

$array = /* your data */; 

$latest = $array; 
uasort($latest, function (array $a, array $b) { 
    return strtotime($a['extra']['date']) - strtotime($b['extra']['date']); 
}); 
array_splice($latest, 2); 

$latestOnTop = array_merge($latest, array_diff_key($array, $latest)); 

array_splice操作需要你的數組鍵實際上product1或類似;將不會與數字索引一起使用,因爲它們將被重新編號。如果是這種情況,請使用另一個截斷機制。

如果你的數組非常大,那麼完整的排序將會不必要的緩慢。在這種情況下,您應該循環一次數組,記錄您可以找到的兩個最新項目(及其鍵),然後array_diff_keyarray_merge就可以了。這實施起來有點困難(留給讀者練習),但效率更高。