php - 使用 uasort 的排序函数

标签 php algorithm

我正在尝试为我的多维数组创建排序函数,但我无法弄清楚算法。

下面是我要排序的数组的例子

[test1] => Array
    (
        [soldAvg] => 3
        [inStock] => 100
    )

[test2] => Array
    (
        [soldAvg] => 3
        [inStock] => 0
    )

[test3] => Array
    (
        [soldAvg] => 113
        [inStock] => 31
    )

[test4] => Array
    (
        [soldAvg] => 4
        [inStock] => 1
    )

[test5] => Array
    (
        [soldAvg] => 3
        [inStock] => 1
    )

我想按照 soldAvg 和 inStock 之间的最大差异对数组进行排序

所以数组应该像下面这样

 [test1] => Array
    (
        [soldAvg] => 3
        [inStock] => 100
    )
 [test3] => Array
    (
        [soldAvg] => 113
        [inStock] => 31
    )
 [test4] => Array
    (
        [soldAvg] => 4
        [inStock] => 1
    )
 [test2] => Array
    (
        [soldAvg] => 3
        [inStock] => 0
    )
 [test5] => Array
    (
        [soldAvg] => 3
        [inStock] => 1
    )

我真正头疼的是当inStock大于sold avg时我不知道该怎么办

我工作附近唯一的事情就是

 function usortAlgo($a,$b)
 {
   if($a['soldAvg']*2 / $a['inStock'] == $b['soldAvg']*2 / $b['inStock'])
    return 0;
   if($a['soldAvg']*2 / $a['inStock'] > $b['soldAvg']*2 / $b['inStock'])
    return -1;
   if($a['soldAvg']*2 / $a['inStock'] < $b['soldAvg']*2 / $b['inStock'])
    return 1;
 }

但是如果 inStock 大于 soldAvg,它就不起作用,如果 soldAvg 是 0,我会得到这个错误“除以零”

最佳答案

我知道您发布这个问题已经有一段时间了,但我最近做了一些与您所问的类似的事情,因为它可能会帮助 stackoverflow 的其他访问者:

/**
 * function used in sortByDiff() sort the array
 * @param  mixed $a [description]
 * @param  mixed $b [description]
 * @return int      The comparison function must return an integer less than, equal to,
 *                  or greater than zero if the first argument is considered to be
 *                  respectively less than, equal to, or greater than the second.
 */
function cmp($a, $b) {
    if ($a == $b)
        return 0;
    return ($a['diff'] < $b['diff']) ? -1 : 1;
}

/**
 * sort an array in order of the diffence between to nested values
 * @param  array   $toSort     the array to sort
 * @param  String  $valueName1 name of the first index
 * @param  String  $valueName2 name of the second index
 * @param  boolean $rev        true|false reverse the order if true
 * @return array               the sorted array
 */
function sortByDiff(array $toSort, $valueName1, $valueName2, $rev = false)
{
    $sorted = $toSort;
    foreach ($toSort as $key => $elem) {
        $val1 = getValue($elem, array($valueName1));
        $val2 = getValue($elem, array($valueName2));
        if ($val1 === null || $val2 === null)
            return null;
        $sorted[$key]['diff'] = abs($elem[$valueName1] - $elem[$valueName2]);
    }
    uasort($sorted, 'cmp');
    foreach ($sorted as $key => $elem)
        unset($sorted[$key]['diff']);
    if ($rev === true)
        return array_reverse($sorted);
    return $sorted;
}

/**
* @param  array  $array      The array from which to get the value
 * @param  array  $parents    An array of parent keys of the value,
 *                            starting with the outermost key
 * @param  bool   $key_exists If given, an already defined variable
 *                            that is altered by reference
 * @return mixed              The requested nested value. Possibly NULL if the value
 *                            is NULL or not all nested parent keys exist.
 *                            $key_exists is altered by reference and is a Boolean
 *                            that indicates whether all nested parent keys
 *                            exist (TRUE) or not (FALSE).
 *                            This allows to distinguish between the two
 *                            possibilities when NULL is returned.
 */
function &getValue(array &$array, array $parents, &$key_exists = NULL)
{
    $ref = &$array;
    foreach ($parents as $parent) {
        if (is_array($ref) && array_key_exists($parent, $ref))
            $ref = &$ref[$parent];
        else {
            $key_exists = FALSE;
            $null = NULL;
            return $null;
        }
    }
    $key_exists = TRUE;
    return $ref;
}

示例:

$toSort = [
    'test1' => [
        'soldAvg' => 3,
        'intStock' => 100,
    ],
    'test2' => [
        'soldAvg' => 3,
        'intStock' => 0,
    ],
    'test3' => [
        'soldAvg' => 113,
        'intStock' => 31,
    ],
    'test4' => [
        'soldAvg' => 4,
        'intStock' => 1,
    ],
    'test5' => [
        'soldAvg' => 3,
        'intStock' => 1,
    ],
];

$sorted = sortByDiff($toSort, 'soldAvg', 'intStock', true);
print_r($sorted);

如预期的输出:

Array
(
    [test1] => Array
        (
            [soldAvg] => 3
            [intStock] => 100
        )

    [test3] => Array
        (
            [soldAvg] => 113
            [intStock] => 31
        )

    [test2] => Array
        (
            [soldAvg] => 3
            [intStock] => 0
        )

    [test4] => Array
        (
            [soldAvg] => 4
            [intStock] => 1
        )

    [test5] => Array
        (
            [soldAvg] => 3
            [intStock] => 1
        )
)

关于php - 使用 uasort 的排序函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25506636/

相关文章:

php - 查询后从数组中获取正确的数据?

javascript - 获取和设置 localStorage 中的 javascript 值

java - 如何将 WaitForMultipleObjects 移植到 Java?

algorithm - 如果使用 BFS 检查添加边是否会产生环路,Kruskal 算法的整体 Big O 运行时间是多少?

algorithm - 旋转 N 位字的高效排序

javascript - 如何使用VBS或BAT脚本发送url请求

php - 关于 unix 时间戳

php - 如何在来自 php 的 ajax JSON 响应中的字符串中添加双引号?

c++ - bin排序的问题

algorithm - 行进立方体效率 - 你可以减少 3/4rs 的边缘计算吗?