mintobit
mintobit

Reputation: 2383

Custom sort the keys of a flat associative array

I'm having an array of data like this:

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

I need it to be sorted to this:

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

I believe this can be done via uksort, but I can't find the solution of custom_sort function.

Upvotes: 0

Views: 192

Answers (4)

Seder
Seder

Reputation: 2763

This will sort the array descending based on the array key

You want to sort the array descending so you can use this function krsort which will sort the array based on the key descending and I will put them in new array named 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); 
?> 

Upvotes: 0

nickb
nickb

Reputation: 59699

It looks like the sorting is done by string length, then by alphabetical ordering. That's not too hard to accomplish using uksort!

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

uksort( $array, 'cmp');

Output:

// 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.

Upvotes: 1

Kevin Vandenborne
Kevin Vandenborne

Reputation: 1387

I have a set of such arrays but not sorted. I'll be inserting the values to the database with a single query, like INSERT INTO table (unique_ids,unique_ips,total_ids,total_ips,global) VALUES (...),(...),(...) etc. Thats why i need the arrays of this set to be sorted identically

So why not do something like

$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) . ')'

Quickly typed it, expect some syntax errors.

Upvotes: 0

Scuzzy
Scuzzy

Reputation: 12332

This seems rather pointless, can you provide a reason why you need this? I assume it's something to do with a looped output.

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

Upvotes: 5

Related Questions