简体   繁体   中英

Sort multidimensional array prioritising substring

I have a multi-dimensional array to work with and sort in PHP. I am trying to sort it by the product_code key. The array needs to be arranged

  • first in the ascending order of the last two characters of product_code
  • then in the ascending order of the characters preceding the '.' of product_code

Here is the array I have

Array

(
    [0] => Array
        (
            [product_name] => Stellar
            [product_code] => C5311.01
        )

    [1] => Array
        (
            [product_name] => Luigi
            [product_code] => C5310.02
        )

    [2] => Array
        (
            [product_name] => Apple
            [product_code] => C5310.01
        )

    [3] => Array
        (
            [product_name] => Quietly
            [product_code] => C5311.02
        )
)

This needs to be sorted as:

Array
(
    [0] => Array
        (
            [product_name] => Apple
            [product_code] => C5310.01
        )


    [1] => Array
        (
            [product_name] => Stellar
            [product_code] => C5311.01
        )

    [2] => Array
        (
            [product_name] => Luigi
            [product_code] => C5310.02
        )


    [3] => Array
        (
            [product_name] => Quietly
            [product_code] => C5311.02
        )

)

I thought sorting the array by product_code key first and then by the substring using usort would yield me favourable results, but I was wrong. Maybe I am trying too hard..

Any help would be highly appreciated. Thanks in advance.

I think that usort is actually what you need, but I think you are wrong in the way you are using it. If you need to sort

  • first in the ascending order of the last two characters of product_code
  • then in the ascending order of the characters preceding the '.' of product_code

just write a function which do this and pass it to usort :

function cmp($a,$b){
      $lastTwoDigitsCmp=strcmp(substr($a["product_code"], -2), substr($b["product_code"], -2));
      if($lastTwoDigitsCmp==0)
          return strcmp($a["product_code"],$b["product_code"]);
      else
          return $lastTwoDigitsCmp;

}

This should do the job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM