0

Okay, I'm officially going nuts. I have tried all solutions found online, however none is working.

I have this array:

$hits = array(
    array('sortby' => 'String 1', 'html' => '<div>This element contains String 1</div>',
    array('sortby' => 'String 11', 'html' => '<div>This element contains String 11</div>',
    array('sortby' => 'String 2', 'html' => '<div>This element contains String 2</div>',
);

I want to sort the $hits array naturally by the "sortby" key, so the output becomes like this:

 <div>This element contains String 1</div>
 <div>This element contains String 2</div>
 <div>This element contains String 11</div>

Which sort function could I use?

1
  • You probably have to write your own function. Commented Apr 9, 2015 at 9:27

3 Answers 3

3

Simply use usort(), with a strnatcmp() comparison.

$hits = array(
    array('sortby' => 'String 1', 'html' => '<div>This element contains String 1</div>'),
    array('sortby' => 'String 11', 'html' => '<div>This element contains String 11</div>'),
    array('sortby' => 'String 2', 'html' => '<div>This element contains String 2</div>')
);

usort($hits, function($a, $b) {
    return strnatcmp($a['sortby'], $b['sortby']);
});

var_dump($hits);

/*
array(3) {
  [0]=>
  array(2) {
    ["sortby"]=>
    string(8) "String 1"
    ["html"]=>
    string(41) "<div>This element contains String 1</div>"
  }
  [1]=>
  array(2) {
    ["sortby"]=>
    string(8) "String 2"
    ["html"]=>
    string(41) "<div>This element contains String 2</div>"
  }
  [2]=>
  array(2) {
    ["sortby"]=>
    string(9) "String 11"
    ["html"]=>
    string(42) "<div>This element contains String 11</div>"
  }
}
*/
Sign up to request clarification or add additional context in comments.

Comments

1
usort($hits, function($a, $b){
    return strnatcmp($a['sortby'], $b['sortby']);
});

3 Comments

as he wanted it naturally sorted: function ($a, $b) { return strnatcmp($a['sortby'], $b['sortby']); }
It's definitely not naturally sorted: 11, 2, 473, 5 instead of 2, 5, 11, 473
@JensSchulze I missed "naturally" part thanks for fix
0

Try below :

<?php
$hits = array(
    array('sortby' => 'String 1', 'html' => '<div>This element contains String 1</div>'),
    array('sortby' => 'String 11', 'html' => '<div>This element contains String 11</div>'),
    array('sortby' => 'String 2', 'html' => '<div>This element contains String 2</div>')
);

function comp($a, $b) {
    $n1 = intval(substr($a['sortby'], 7));
    $n2 = intval(substr($b['sortby'], 7));
    return $n1>$n2;
}

usort($hits, "comp");

print_r($hits);

?>

Using usort(), you can apply your sort rule.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.