【问题标题】:how to sort an array based on a different array in php? [closed]如何根据php中的不同数组对数组进行排序? [关闭]
【发布时间】:2014-01-14 20:28:00
【问题描述】:

我有这个数组

array(
    'pc' => array('count'=>3),
    'xbox' => array('count'=>3),
    'wii' => array('count'=>3),
    '3ds' => array('count'=>3),
    'other' => array('count'=>3),
)

我想像这样订购它

array(
    'wii' => array('count'=>3),
    'xbox' => array('count'=>3),
    'other' => array('count'=>3),
    '3ds' => array('count'=>3),
    'pc' => array('count'=>3),
)

我认为我需要另一个数组来排序??

键可能不一样,所以我认为isset() 是有顺序的

编辑:条件是第二个数组键

有什么想法吗?

【问题讨论】:

  • 排序的标准是什么?我没有看到。
  • 对我来说似乎很随机@JohnConde
  • 编辑:条件是第二个数组键

标签: php arrays sorting associative-array


【解决方案1】:

您必须定义自定义排序算法。您可以使用 PHP 的 uksort() 函数来做到这一点。 (与非常相似的 usort() 函数的区别在于它比较数组的键而不是其值。)

它可能看起来像这样(需要 PHP >= 5.3,因为我在其中使用了匿名函数):

<?php
$input = array(
    'pc' => array('count'=>3),
    'xbox' => array('count'=>3),
    'wii' => array('count'=>3),
    '3ds' => array('count'=>3),
    'other' => array('count'=>3),
);
$keyOrder = array('wii', 'xbox', 'other', '3ds', 'pc');

uksort($input, function($a, $b) use ($keyOrder) {
    // Because of the "use" construct, $keyOrder will be available within
    // this function.
    // $a and $b will be two keys that have to be compared against each other.

    // First, get the positions of both keys in the $keyOrder array.
    $positionA = array_search($a, $keyOrder);
    $positionB = array_search($b, $keyOrder);

    // array_search() returns false if the key has not been found. As a
    // fallback value, we will use count($keyOrder) -- so missing keys will
    // always rank last. Set them to 0 if you want those to be first.
    if ($positionA === false) {
        $positionA = count($keyOrder);
    }
    if ($positionB === false) {
        $positionB = count($keyOrder);
    }

    // To quote the PHP docs:
    // "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."
    return $positionA - $positionB;
});

print_r($input);

【讨论】:

  • 似乎可以满足我的需求。谢谢
猜你喜欢
  • 2013-05-19
  • 2023-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-17
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多