2011-11-27 48 views
0

的:自定义排序我有数据的一个这样的数组的数组

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

+3

你想要的排序顺序是没有意义的我。你能详细说明吗?它遵循什么规则? –

+0

我有一组这样的数组,但没有排序。我会用一个查询中插入值到数据库中,像INSERT INTO'table'('unique_ids','unique_ips','total_ids','total_ips','global')VALUES(...),( ...),(...)等,这就是为什么我需要这个集合的数组排序相同。 – mintobit

+1

谢谢大家的快速回复!看到这里的整个问题帮助了我。 >我需要将这个集合的数组进行排序。这意味着我可以按照字母顺序排序它们。这样他们排序相同,我可以在查询中使用它们。顺便说一下,我想要的排序逻辑很奇怪。我真的很抱歉,我让你在这个问题上浪费你的时间。 – mintobit

回答

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

这将数组降序排序基于阵列的关键

你想在阵列下降,所以你可以使用这个功能krsort将基于密钥下降和我排序的数组排序这将使他们在新的数组排序命名的数组

<?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); 
?> 
+0

不产生OP的所需输出。因为krsort是就地,以及[按键混淆在一起(http://codepad.org/3IN9Wxfb)你不需要foreach循环。 – nickb

+0

是的,但它确实命令他们 – Sedz

+0

对不起,你是对的,我没有看到身份证和IP – Sedz

0

我有一组这样的阵列,但不排序。我会用一个查询中插入值到数据库中,像INSERT INTO表(unique_ids,unique_ips,total_ids,total_ips,全球)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) . ')' 

快速键入它,期待一些语法错误。

+0

**在单个查询中的数组集合**'INSERT INTO表(unique_ids,unique_ips,total_ids,total_ips,global)VALUES('0','0','0' , '0', '0'),( '0', '0', '0', '0', '0'),( '0', '0', '0', '0',” 0')...'如果将不被排序,值会混淆。 – mintobit

+0

所以只是做INSERT INTO表(unique_ids,unique_ips,total_ids,total_ips,全球)VALUES($阵列[ 'unique_ids'],$阵列[ 'unique_ips'],$阵列[ 'total_ids'],$阵列[ 'total_ips' ],$ array ['global'])创建一个向查询添加更多数据的循环并不难。我不明白这有什么困难。 –

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