Click here to Skip to main content
16,018,057 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
PHP
Array
(
    [0] => stdClass Object
        (
            [posts] => 29
            [term_id] => 49
        )

    [1] => stdClass Object
        (
            [posts] => 2
            [term_id] => 54
        )

    [2] => stdClass Object
        (
            [posts] => 11
            [term_id] => 36
        )

)


How I can sort this array by no of posts?

like 2,11,29

What I have tried:

PHP
function cmp($a, $b)
{
    if ($a["posts"] == $b["posts"]) {
        return 0;
    }
    return ($a["posts"] < $b["posts"]) ? -1 : 1;
}

usort ($array_o, "cmp");
Posted
Updated 22-Jan-18 0:50am
v3
Comments
Patrice T 19-Jan-18 22:13pm    
What is the problem?
No documentation ? no tuto on sort?

This might be helpful - Native PHP Sort array of objects by property – Tormix Blog – Web development[^]

PHP
<?php

 $attachment_ids = array();
    $attachment_ids[0]['posts'] = 29;
    $attachment_ids[0]['term_id'] = 49;
    $attachment_ids[1]['posts'] = 2;
    $attachment_ids[1]['term_id'] = 54;
    $attachment_ids[2]['posts'] = 11;
    $attachment_ids[2]['term_id'] = 36;
    $attachment_ids                 = json_encode($attachment_ids);
    $attachment_ids                 = json_decode($attachment_ids, FALSE);
   // print_r($attachment_ids);


function sortArrayWithObjects($array, $property)
{
    usort($array, function ($a, $b) use ($property) {
        return (($a->$property == $b->$property) ? 0 : (($a->$property < $b->$property) ? -1 : 1));
        //[short version] return strcmp($a->$property, $b->$property);
    });
    return $array;
}

$result = sortArrayWithObjects($attachment_ids, 'posts');
echo '<pre>';
var_dump($result);
echo '</pre>';
?>


Output:
array(3) {
  [0]=>
  object(stdClass)#2 (2) {
    ["posts"]=>
    int(2)
    ["term_id"]=>
    int(54)
  }
  [1]=>
  object(stdClass)#3 (2) {
    ["posts"]=>
    int(11)
    ["term_id"]=>
    int(36)
  }
  [2]=>
  object(stdClass)#1 (2) {
    ["posts"]=>
    int(29)
    ["term_id"]=>
    int(49)
  }
}
 
Share this answer
 
Warning: usort() expects parameter 1 to be array, null given in /home/dposts1/public_html/demo/wp-content/plugins/wp-random-date-post/category-posts.php on line 26


Not working
 
Share this answer
 
Comments
Patrice T 22-Jan-18 7:27am    
Use Improve question to update your question.
And delete this non solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900