【问题标题】:Sorting an array based on the order of a separate array根据单独数组的顺序对数组进行排序
【发布时间】:2011-02-25 11:34:58
【问题描述】:

我编写的代码基于this similar question,但是我无法将其转换为在一个类中工作并且不使用全局变量

这就是我想要做的。

假设我有 2 个数组:

$headings = array(
    'id' => 'ID',
    'name' => 'Name',
);

$rows = array(
    array(
        'id' => 1,
        'name' => 'Jo Blogs',
    ),
    array(
        'name' => 'John Smith',
        'id' => 2,
        'other' => 'Potentially other data'
    ),
);

我想将$rows 排序为$headings 中指定的顺序,最后出现任何未定义的键。例如,在对$rows 进行排序后会如下所示:

$rows = array(
    array(
        'id' => 1,
        'name' => 'Jo Blogs',
    ),
    array(
        'id' => 2,
        'name' => 'John Smith',
        'other' => 'Potentially other data'
    ),
);

在类之外工作的代码是

$headings = array(
    'id' => 'ID',
    'name' => 'Name',
);

$rows = array(
    array(
        'id' => 1,
        'name' => 'Jo Blogs',
    ),
    array(
        'name' => 'John Smith',
        'id' => 2,
        'other' => 'Potentially other data'
    ),
);

var_dump($rows);

array_walk($rows, "sort_it");

var_dump($rows);

function sort_it(&$value, $key) {
    uksort($value, "cmp");
}

function cmp($a, $b) {
    global $headings;

    if (!isset($headings[$a]) || !isset($headings[$b]) || $headings[$a]>$headings[$b]){
        return 1;
    }else{
        return -1;
    }

}

然后输出:

array
  0 => 
    array
      'id' => int 1
      'name' => string 'Jo Blogs' (length=8)
  1 => 
    array
      'name' => string 'John Smith' (length=10)
      'id' => int 2
      'other' => string 'Potentially other data' (length=22)
array
  0 => 
    array
      'id' => int 1
      'name' => string 'Jo Blogs' (length=8)
  1 => 
    array
      'id' => int 2
      'name' => string 'John Smith' (length=10)
      'other' => string 'Potentially other data' (length=22)

这是正确的。再说一遍,我如何摆脱对全局的使用。我知道array_walk($rows, array($this, "sort_it")); 将使用$this->sort_it()。不幸的是,这必须在 PHP 5.2.14 中工作(所以从 5.3 开始没有花哨的花哨)。

谢谢。

【问题讨论】:

  • 您需要兼容低于 5.3 的 PHP 版本吗?
  • @BoltClock - 不幸的是。 5.2.14。我也会将其添加到问题中,谢谢。

标签: php arrays sorting


【解决方案1】:
$result = fix_array_order($rows, $headings);
print_r($result);

function fix_array_order($array, $order_array)
{
    $order = array_keys($order_array);

    $result = array();
    foreach($array as $arr)
    {
        $new_sub_array = array();
        foreach($order as $key)
        {
            $new_sub_array[$key] = $arr[$key];
        }

        $diff = array_diff(array_keys($arr), $order);
        foreach($diff as $diff_key)
        {
        $new_sub_array[$diff_key] = $arr[$key];
        }
        $result[] = $new_sub_array;
    }
    return $result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 2019-08-04
    • 2014-10-02
    • 1970-01-01
    相关资源
    最近更新 更多