2

I am trying to order the elements of an array by the following two ways:

  • Sort by key length (smallest should go first) - See here
  • Max value should go first

To sort by key length I use this:

    function sortByLength($a,$b){
      if($a == $b) return 0;
      return (strlen($a) < strlen($b) ? -1 : 1);
    }

    uasort($deals_tag,'sortByLength');

And the array is sorted that way:

Array
(
 [/merchantProductFeed] => 1
 [/merchantProductFeed/merchant] => 1
 [/merchantProductFeed/merchant/prod/text] => 158
 [/merchantProductFeed/merchant/prod] => 158
)

I want it to be sorted like this:

Array
(
 [/merchantProductFeed/merchant/prod] => 158
 [/merchantProductFeed/merchant/prod/text] => 158
 [/merchantProductFeed] => 1
 [/merchantProductFeed/merchant] => 1
)

Notice that first the array is sorted by key length and then by max value.

I don't know how to do that.

Any help would be highly appreciated! Thank you!

2
  • 2
    You can simplify sortByLength(): return strlen($a) - strlen($b); Commented Jul 29, 2012 at 5:30
  • uasort is sort by value, not by key. Commented Jul 29, 2012 at 5:33

2 Answers 2

1

updated: you can use array_mulitsort. try

$k= array();
$v = array();

foreach($deals_tag as $key => $value){
    $k[] = $key;
    $v[] = $value;
}

array_multisort($v, SORT_DESC, $k, SORT_ASC,  $deals_tag);
Sign up to request clarification or add additional context in comments.

2 Comments

I tried that and I get [/merchantProductFeed] => 1, [/merchantProductFeed/merchant] => 1, [/merchantProductFeed/merchant/prod] => 158, [/merchantProductFeed/merchant/prod/text] => 158
You're a life saver! Thank you so much for this! Really gave me a helping hand!
1

I know it might be a little bit overhead but a different way to sort things is by using a (temporary) DB, I use it personally if I need some "hardcore" sorting so here it is...

<?php
$p = new PDO("sqlite::memory:");
$p->exec("CREATE TABLE a (k varchar(255),v int)");

$p->exec("INSERT INTO a (k,v) VALUES('/merchantProductFeed',1)");
$p->exec("INSERT INTO a (k,v) VALUES('/merchantProductFeed/merchant',1)");
$p->exec("INSERT INTO a (k,v) VALUES('/merchantProductFeed/merchant/prod/text',158)");
$p->exec("INSERT INTO a (k,v) VALUES('/merchantProductFeed/merchant/prod',158)");

$st=$p->query("SELECT * FROM a ORDER BY length(k) DESC,v DESC");
print_r($st->fetchAll());
?>

I donÄt know how long your string is, in this example I used varchar(255) if it is longer you should use TEXT.

1 Comment

I do appreciate that you took the time to write an answer but in my case the string /merchantProductFeed/merchant/prod is saved in the database as an entire string and then I break it into parts by using explode.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.