自定义排序数组

时间:2011-11-27 22:13:33

标签: php arrays

我有这样的数据数组:

$array = array(
'total_ids' => 0,
'unique_ips' => 0,
'unique_ids' => 0,
'global' => 0,
'total_ips' => 0,
);

我需要将它分类到:

$array = array(
'unique_ids' => 0,
'unique_ips' => 0,
'total_ids' => 0,
'total_ips' => 0,
'global' => 0
);

我相信这可以通过uksort完成,但我无法找到custom_sort函数的解决方案。

4 个答案:

答案 0 :(得分:5)

这似乎毫无意义,你能提供一个你需要它的原因吗?我认为它与循环输出有关。

$new_array = array(
  'unique_ids' => $array['unique_ids'],
  'unique_ips' => $array['unique_ips'],
  'total_ids' => $array['total_ids'],
  'total_ips' =>$array['total_ips'],
  'global' => $array['global']
);
$array = $new_array;

答案 1 :(得分:1)

看起来排序是通过字符串长度完成的,然后按字母排序完成。使用uksort来完成这一点并不难:

function cmp( $a, $b) 
{
    if( strlen( $a) != strlen( $b))
    {
        return strlen( $a) < strlen( $b) ? 1 : -1;
    }
    return strcasecmp( $a, $b);
}

uksort( $array, 'cmp');

<强>输出:

// Before uksort()
array(5) {
  ["total_ids"]=>
  int(0)
  ["unique_ips"]=>
  int(0)
  ["unique_ids"]=>
  int(0)
  ["global"]=>
  int(0)
  ["total_ips"]=>
  int(0)
}
// After uksort()
array(5) {
  ["unique_ids"]=>
  int(0)
  ["unique_ips"]=>
  int(0)
  ["total_ids"]=>
  int(0)
  ["total_ips"]=>
  int(0)
  ["global"]=>
  int(0)
}

See the magic

答案 2 :(得分:0)

这将根据数组键

对数组进行降序排序

您希望对数组进行降序排序,以便您可以使用此函数krsort,它将根据键降序对数组进行排序,并将它们放入名为sorted array的新数组中

<?php
$array = array(
    'total_ids' => 0,
    'unique_ips' => 0,
    'unique_ids' => 0,
    'global' => 0,
    'total_ips' => 0,
    );
    krsort($array);
    $sorted_array = array(); 
foreach ($array as $key => $value) {
    $sorted_array[$key] = $value; 
}
print_r($sorted_array); 
?> 

答案 3 :(得分:0)

  

我有一组这样的数组但没有排序。我将使用单个查询将值插入数据库,例如INSERT INTO表(unique_ids,unique_ips,total_ids,total_ips,global)VALUES(...),(...),(...)等。这就是为什么我需要这个数组的数组相同排序

那么为什么不做像

这样的事情
$array = array(
'total_ids' => 0,
'unique_ips' => 0,
'unique_ids' => 0,
'global' => 0,
'total_ips' => 0,
);


 'INSERT INTO table(' . implode(', ', array_keys($array)) . ') VALUES (' . implode(', ', $array) . ')'

快速输入,预计会出现一些语法错误。

相关问题