0

I have an array and I want change it's order. Following is an my 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
                )    

index [2] array should be come at last because it contains value [B] = RTN Means I want to reorder this array if [B] index contains value RTN should be come at last

Final output should be

  [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
                    )    
3
  • did u tried anything? Commented Sep 29, 2016 at 10:06
  • I havent tried anything. I am not able find any way Commented Sep 29, 2016 at 10:06
  • what is the business logic of this reordering?otherwise just grab the arraykey & unset them & then push into the array again Commented Sep 29, 2016 at 10:19

2 Answers 2

2

Is this what your looking for?

foreach ($aArrayToSort as $iPos => $aArray) {
    if($aArray['B'] == 'RTN'){
        $aArrayToSort[] = $aArrayToSort[$iPos];
        unset($aArrayToSort[$iPos]);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I want that RTN records. I dont want to unset that
I'm adding it to the end of the array then removing it. Saved storing it in a temp var. UPDATE - noticed an error in code, see what your saying now.. Updated accordingly
2

You can use usort and provide a function:

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']);
  });

2 Comments

This sorts the arrays ascending, OP wants it descending. You need to switch $arr1['B'] and $arr2['B'] inside strcmp()
Thanks. Fixed it accordingly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.