2016-04-03 81 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