steo
steo

Reputation: 4656

PHP sort array by key names

I have an array like this

//$src
Array(
[dim_55] => path/to/image.jpg
[dim_180] => path/to/image.jpg
[dim_190] => path/to/image.jpg
[dim_475] => path/to/image.jpg
[dim_635] => path/to/image.jpg
[dim_540] => path/to/image.jpg
[dim_1130] => path/to/image.jpg
[dim_1900] => path/to/image.jpg
)

( path/to/image.jpg is a generic path )

I would like to order this by key in an order like

dim_1900
dim_1130
dim_635
dim_540
dim_475
..

To achieve this solution I did something like:

$sortSrc = array();
foreach($src as $key => $value){
  $newkey = explode("dim_", $key);
  $sortSrc[$newkey[1]] = $value; 
}

krsort($sortSrc);

It works but maybe is not so effective. Is there a way in which I can achieve this with native PHP functions?

Upvotes: 0

Views: 105

Answers (4)

Girish
Girish

Reputation: 12127

you can also use custom sort by key numeric with uksort() function, try this code

<?php 
$data = Array(
"dim_55" => "path/to/image.jpg",
"dim_180" => "path/to/image.jpg",
"dim_190" => "path/to/image.jpg",
"dim_475" => "path/to/image.jpg",
"dim_635" => "path/to/image.jpg",
"dim_540" => "path/to/image.jpg",
"dim_1130" => "path/to/image.jpg",
"dim_1900" => "path/to/image.jpg"
);
$sort_data = uksort($data, function($a, $b){
  preg_match("/dim_(\d+)/",$a, $matcha);
  preg_match("/dim_(\d+)/",$b, $matchb);
  if($matcha[1] == $matchb[1]){
    return 0;
  }
  return $matcha[1] > $matchb[1] ? -1 : 1;
});
print_r($data);
?>

DEMO

Upvotes: 0

Henter
Henter

Reputation: 1

#!/usr/bin/env php
<?php
$a = [
    'dim_55' => 'path/to/image.jpg',
    'dim_180' => 'path/to/image.jpg',
    'dim_190' => 'path/to/image.jpg',
    'dim_475' => 'path/to/image.jpg',
    'dim_635' => 'path/to/image.jpg',
    'dim_540' => 'path/to/image.jpg',
    'dim_1130' => 'path/to/image.jpg',
    'dim_1900' => 'path/to/image.jpg',
];

krsort($a, SORT_NATURAL);

print_r($a);

Upvotes: 0

Kremnev Sergey
Kremnev Sergey

Reputation: 332

You need to use krsort($src, SORT_NATURAL);

See: http://php.net/manual/en/function.sort.php for sort flags documentation

Upvotes: 4

Abude
Abude

Reputation: 2162

you should be able to achieve what you want with ksort:

krsort — Sort an array by key in reverse order

 <?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

d = lemon
c = apple
b = banana
a = orange

Upvotes: 0

Related Questions