Home > Software engineering >  How to sort Multi-Dimensional Array by specific value php
How to sort Multi-Dimensional Array by specific value php

Time:10-02

Having a hard time sorting by 'Quote_no' from high to low. How do I access 'Quote_no'? Have tried the following, but it is not sorting. Am I missing something or accessing 'Quote_no' incorrectly?

usort($array, function($x, $y) {
    return $x['attributes']['Quote_no'] <=> $y['attributes']['Quote_no'];
});

example array:

   Array ( 
      [0] => Array ( 
        [attributes] => Array ( 
          [Quote_no] => 224941 
          [Cust_no] => 103992 
          [Contactid] => 219315 
          [Quote_dt] => 2022-09-30T00:00:00 
          [Status] => Open 
          [Valid_days] => 3 
          [Update_dt] => 2022-09-30T07:05:04.993 
        ) 
      ) 
      [1] => Array ( 
        [attributes] => Array ( 
          [Quote_no] => 224936 
          [Cust_no] => 103992 
          [Contactid] => 219315 
          [Quote_dt] => 2022-09-30T00:00:00 
          [Status] => Open 
          [Valid_days] => 3 
          [Update_dt] => 2022-09-30T07:24:59.767 
        ) 
      )
    )

This is the order returned:

224941  Sep, 30, 2022       
224942  Sep, 30, 2022    
224943  Sep, 30, 2022       
224944  Sep, 30, 2022   
224945  Sep, 30, 2022   
224947  Sep, 30, 2022   
224949  Sep, 30, 2022   
223616  Apr, 14, 2022    
222519  Nov, 29, 2021    
222507  Nov, 26, 2021

This is what i am expecting:

224949  Sep, 30, 2022
224947  Sep, 30, 2022
224945  Sep, 30, 2022
224944  Sep, 30, 2022
224943  Sep, 30, 2022
224942  Sep, 30, 2022
224941  Sep, 30, 2022
223616  Apr, 14, 2022
222519  Nov, 29, 2021
222507  Nov, 26, 2021

CodePudding user response:

Your code worked for me. Good use of the spaceship operator. I used the following in https://onlinephp.io/

<?php

$array = Array ( 
     0 => Array ( 
          'attributes' => Array ( 
          'Quote_no' => 224941 ,
          'Cust_no' => 103992 ,
          'Contactid' => 219315, 
          'Quote_dt' => new DateTime(), 
          'Status' => 'Open' ,
          'Valid_days' => 3 ,
          'Update_dt' => new DateTime(),
        ) 
      ) ,
      1 => Array ( 
        'attributes' => Array ( 
          'Quote_no' => 224936 ,
          'Cust_no' => 103992 ,
          'Contactid' => 219315, 
          'Quote_dt' => new DateTime() ,
          'Status' => 'Open' ,
          'Valid_days' => 3 ,
          'Update_dt' => new DateTime(), 
        ) 
      )
    );
    
    usort($array, function($x, $y) {
    return $x['attributes']['Quote_no'] <=> $y['attributes']['Quote_no'];
});
echo print_r($array, TRUE);

CodePudding user response:

I must be tired.. So, to solve this simple problem. I switched the $x and $y in the return:

usort($array, function($x, $y) {
    return $y['attributes']['Quote_no'] <=> $x['attributes']['Quote_no'];
});
  • Related