1

In my code below I would like to sort the array $v by its key title, which has only numeric values.

foreach ($archive_years as $key => $value) {
    $id = str_replace(' ', '', $key);
    echo '
        <button type="button" class="btn btn-info collapsible" data-toggle="collapse" data-target="#archiv_'. $id .'"><h3>'. $key .' </h3></button>
        <div id="archiv_'. $id .'" class="collapse">
            <ul>
    ';
    foreach ($value as $k => $v) {
        ksort($v);
        var_dump($v);
        if (get_page($v['id'])->post_content) {
            echo '<li><h4><a href="'. $v["permalink"] .'">'. $v["title"] .' - '. $v["titel"] .'</a></h4></li>';
        }
        else {
            echo '<li><h4>'. $v["title"] .' - '. $v["titel"] .'</h4></li>';
        }

    }
    echo '</ul></div>';
}

I have tried using ksort($v); but that seems not to work in this case.

This is what echo "<pre/>";print_r($v); returns: enter image description here

Any help would be appreciated!

2
  • what is ther in $v? show us for one by doing echo "<pre/>";print_r($v); Commented Feb 15, 2017 at 11:24
  • @Anant I have updated my question. Commented Feb 15, 2017 at 12:23

1 Answer 1

1

You should use usort, if you need your own compare function.

I.e. you could try something like this:

usort($array, function($a, $b) {
    // should work, as title is numeric. to change the direction
    // just change $a and $b
    return $a['title'] - $b['title'];
});
Sign up to request clarification or add additional context in comments.

4 Comments

I have tested your code but for some reason it is not working for me. The array still can't get sorted by title.
Shouldn't there be a logical comparison sign instead of the minus? (< or >)
Thank you, that actually works! I just had to use it for the array $value instead of $v.
No, you dont need < or >. The compare function expects a value smaller, greater or equal to zero. Eo just doing the math is sufficient.

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.