根据php中的值更改数组顺序

时间:2016-09-29 10:03:47

标签: php arrays sorting multidimensional-array

我有一个数组,我想改变它的顺序。     以下是我的数组

        [1] => Array
                (
                    [A] => 25/02/2016
                    [B] => ZPO
                    [C] => 2
                    [D] => 3
                 )
        [2] =>array (
                    [A] => 25/02/2016
                    [B] => RTN
                    [C] => 2
                    [D] => 3
                )  
       [3] =>array (
                    [A] => 25/02/2016
                    [B] => ZPO
                    [C] => 2
                    [D] => 3
                )    
索引[2]数组应该是最后的,因为它包含值[B] = RTN 意味着如果[B]索引包含值 RTN ,我想重新排序此数组

最终输出应为

  [1] => Array
                    (
                        [A] => 25/02/2016
                        [B] => ZPO
                        [C] => 2
                        [D] => 3
                     )
            [2] =>array (
                        [A] => 25/02/2016
                        [B] => ZPO
                        [C] => 2
                        [D] => 3
                    )  
           [3] =>array (
                        [A] => 25/02/2016
                        [B] => RTN
                        [C] => 2
                        [D] => 3
                    )    

2 个答案:

答案 0 :(得分:2)

您可以使用usort并提供功能:

usort(
  $array,
  // compare function for value 'B'.
  function($arr1, $arr2) { 
      // descending order ($arr2, $arr1). for ascending compare ($arr1, $arr2)
      return strcmp($arr2['B'], $arr1['B']);
  });

答案 1 :(得分:2)

这是你想要的吗?

foreach ($aArrayToSort as $iPos => $aArray) {
    if($aArray['B'] == 'RTN'){
        $aArrayToSort[] = $aArrayToSort[$iPos];
        unset($aArrayToSort[$iPos]);
    }
}