如何通过值php的一部分对关联数组进行排序?

时间:2017-05-15 12:51:34

标签: php arrays laravel sorting

我有一个数组:

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"
  ]
]

我如何实现这一目标?

4 个答案:

答案 0 :(得分: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;
}

但是功能内部的爆炸肯定不是更好。

有关uasort的更多信息,请访问:uasort

答案 1 :(得分:1)

你可以这样做:

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

答案 2 :(得分:1)

您可以使用自定义排序功能执行此操作,例如:

<?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 )

如果你有一个多维数组,你可以遍历所有类别,如&#34; Ice Coffee&#34;并为每个类别运行uasort。

答案 3 :(得分:1)

$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 )