自定义数组类型


Custom sort of an array

我有一个这样的数据数组:

$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函数的解决方案。

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

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

看起来排序是按字符串长度完成的,然后按字母顺序排序。使用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)
}

我有一组这样的数组,但没有排序。我将使用单个查询将值插入数据库,如INSERT INTO table (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) . ')'

快速输入,预料会有语法错误

这将根据数组键

降序排序数组

你想对数组进行降序排序那么你可以使用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); 
?>