带衣服尺寸和附加值的排序数组 [英] Sorting array with clothing sizes and extra values

查看:59
本文介绍了带衣服尺寸和附加值的排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试对属于数组的一些衣服尺寸数组(S M L XL XXL等)进行排序。我可以通过以下功能来完成此操作(由于此地方 Php阵列排序衣服的尺寸(XXS XS SML XL XXL)和动态阵列上的数字):

I am currently trying to sort some clothing size arrays (S M L XL XXL etc.) that belong to an array. I am able to do this via the following function (thanks to this place Php Array Sorting Clothing Sizes (XXS XS S M L XL XXL) and Numbers on a Dynamic Array):

function cmp($a, $b) {

        $sizes = array(
        "XXS" => 0,
        "XS" => 1,
        "S" => 2,
        "M" => 3,
        "L" => 4,
        "XL" => 5,
        "XXL" => 6
        );

        $asize = $sizes[$a];
        $bsize = $sizes[$b];

        if ($asize == $bsize) {
            return 0;
        }

        return ($asize > $bsize) ? 1 : -1;

    }

    usort($the_array, "cmp");

对于看起来像这样的数组,这很好:$ the_array( S, M, XL)。
但是,我的数组看起来像这样:

This is all very well for an array that looks like this: $the_array("S", "M", "XL"). However, my array looks a bit like this:

$the_array = array("S : price £10", "XXL : price £10", "M : price £10", "XS : price £10")

这使它无法工作...我需要一个函数,理想情况下该函数只能查看数组的第一部分,直到:为止。有这样的事情吗?

This makes it not work... I need a function that ideally only looks at the first part of the array up to the ":". Is there such a thing?

感谢您的帮助。

推荐答案

此解决方案将在每个字符串的开头搜索大小值。只要没有大小是其他大小的前缀(例如 X将是 XL的前缀),它就可以工作。它不依赖于您数据的特定格式;

This solution will search the beginning of each string for the size values. It only works so long as no size is the prefix of another size, such as 'X' would be a prefix of 'XL'. It doesn't rely on the particular format of your data; it will find the earliest occurrence of a valid size string.

// Your comparison function:
function cmp($a, $b) {
  // Make the array static for performance.
  static $sizes = array('XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL');

  // Find the size of $a and $b (the first string for which strpos===0)
  $asize = 100; // Sort non-size strings after matching sizes.
  $apos = -1;
  $bsize = 100;
  $bpos = -1;
  foreach ($sizes AS $val => $str) {
    // It's important to use `===` because `==` will match on
    // FALSE, which is returns for no match.
    if (($pos = strpos($a, $str)) !== FALSE && ($apos < 0 || $pos < $apos)) {
      $asize = $val;
      $apos = $pos;
    }
    if (($pos = strpos($b, $str)) !== FALSE && ($bpos < 0 || $pos < $bpos)) {
      $bsize = $val;
      $bpos = $pos;
    }
  }

  return ($asize == $bsize ? 0 : ($asize > $bsize ? 1 : -1));
}

usort($the_array, 'cmp');

这篇关于带衣服尺寸和附加值的排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆