2016-04-03 64 views
1

的一部分,我有這樣的排序的PHP數組是另一個數組

"entry a" => [ 
    "type": 3, 
    "id": 1, 
    "content" => [ 
     [ 
      "name" => "somename a", 
      "date": => "2011-08-2" 
     ], 
     [ 
      "name" => "somename b", 
      "date": => "2012-04-20" 
     ], 
     [ 
      "name" => "somename c", 
      "date": => "2015-01-14" 
     ], 
    ] 
], 
"entry b" => [ 
    "type": 3, 
    "id": 2, 
    "content" => [ 
     [ 
      "name" => "someothername a", 
      "date": => "2011-01-6" 
     ], 
     [ 
      "name" => "someothername b", 
      "date": => "2015-12-24" 
     ], 
     [ 
      "name" => "someothername c", 
      "date": => "2016-01-01" 
     ], 
    ] 
], 
... 

我想排序只是「內容」排列,按日期,每個條目的數組。我嘗試了以下;

 foreach ($cfArray as $cfEntry) { 
      if($cfEntry['type'] == '3' && !is_null($cfEntry['content'])) { 
       $content = $cfEntry['content']; 
       uasort($content, function($a, $b) { 
        $a_end = strtotime($a['date']); 
        $b_end = strtotime($b['date']); 
        return ($a_end > $b_end) ? -1 : 1; 
       }); 
       $cfEntry['content'] = $content; 
      } 
     } 

如果在排序前後比較$內容,它已更改,但我的$ cfArray不會更改。這是爲什麼?有沒有另一種方法來排序呢?

+0

在計算器鎖定陣列multisort。你問題dublikate – Naumov

+0

http://stackoverflow.com/questions/35097681/sorting-3-dimensional-array-at-2nd-level-based-on-3rd-level-values例如 – Naumov

+0

爲什麼你只用「 「type」:3'? – RomanPerekhrest

回答

1

你的代碼幾乎是工作,你可以創建與保存更改的項目$newCfArray陣列,該樣品完全正常:

$newCfArray = array(); 
foreach ($cfArray as $key => $cfEntry) { 
    if($cfEntry['type'] == '3' && !is_null($cfEntry['content'])) { 
     $content = $cfEntry['content']; 
     uasort($content, function($a, $b) { 
      $a_end = strtotime($a['date']); 
      $b_end = strtotime($b['date']); 
      return ($a_end > $b_end) ? -1 : 1; 
     }); 
     $cfEntry['content'] = $content; 
    } 
    $newCfArray[$key] = $cfEntry; 
} 
$cfArray = $newCfArray; 
+1

嘿謝謝你!完美的作品。我也注意到'uasort'在我的情況下是錯誤的。我現在使用'usort'。但那是一個不同的問題。 =) – Dafen

相關問題