【问题标题】:How to sort an associative array by a part of a value php?如何按值php的一部分对关联数组进行排序?
【发布时间】:2017-10-14 06:31:03
【问题描述】:

我有一个数组:

array:1 [▼
  "Ice Coffee" => array:2 [▼
    0 => "4,78"
    1 => "7,57"
    2 => "12,61"
    3 => "2,89"
  ]
]

我需要根据逗号后面的值对其进行排序,这可能吗?

57 -> 61 -> 78 -> 89

所以结果会是:

array:1 [▼
  "Ice Coffee" => array:2 [▼
    0 => "7,57"
    1 => "12,61"
    2 => "4,78"
    3 => "2,89"
  ]
]

我如何做到这一点?

【问题讨论】:

  • usor 会帮助你

标签: php arrays laravel sorting


【解决方案1】:

uasort 可以像这样处理这种问题:

$test = [
"Ice Coffee" => [
        0 => "4,78",
        1 => "7,57",
        2 => "12,61",
        3 => "2,89"
    ]
];
uasort($test['Ice Coffee'], 'test');
function test($a, $b)
{
    if(explode(',', $a)[1] == explode(',', $b)[1])
    {
        return 0;
    }
    return (explode(',', $a)[1] < explode(',', $b)[1]) ? -1 : 1;
}

但是函数内部的explode肯定不是更好的做法。

更多关于uasort的信息在这里:uasort

【讨论】:

    【解决方案2】:

    你可以这样做:

    usort($array, function ($item1, $item2) {
    list($first,$first1) = split(',',$item1);
    list($second,$second1) = split(',',$item2);
    if ($first == $second) return 0;
    return $first < $second ? -1 : 1;
    });
    

    【讨论】:

      【解决方案3】:

      您可以使用自定义排序功能来做到这一点,例如:

      <?php
      $array = [0 => "4,78", 1 => "7,57", 2 => "12,61", 3 => "2,89"];
      
      function order_behind_comma($a, $b) {
          $_a = explode(",", $a); $_a = intval($_a[1]);
          $_b = explode(",", $b); $_b = intval($_b[1]);
      
          if($_a == $_b) return 0;
          return ($_a < $_b) ? -1 : 1;
      }
      
      uasort($array, 'order_behind_comma');
      print_r($array);
      

      这将返回:

      Array ( [1] => 7,57 [2] => 12,61 [0] => 4,78 [3] => 2,89 )
      

      如果您有一个多维数组,您可以遍历所有类别,例如“Ice Coffee”,并为每个类别运行 uasort。

      【讨论】:

        【解决方案4】:
        $array = ["7,57", "12,61", "4,78", "2,89"];
        
        usort($array, function ($a, $b) {
            $a = explode(',', $a)[1];
            $b = explode(',', $b)[1];
        
            if ($a == $b) {
                return 0;
            }
        
            return ($a < $b) ? -1 : 1;
        });
        
        print_r($array);
        
        // Array ( [0] => 7,57 [1] => 12,61 [2] => 4,78 [3] => 2,89 )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-04-06
          • 1970-01-01
          • 2011-07-09
          • 1970-01-01
          • 2011-06-01
          • 2017-12-01
          • 2013-05-11
          相关资源
          最近更新 更多