Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I have an object array

 <pre>stdClass Object
(
    [October] => 13.88888888888889
    [January] => 11.11111111111111
    [April] => 17.77777777777778
    [February] => 12.777777777777777
    [August] => 17.77777777777778
    [June] => 16.11111111111111
    [May] => 16.11111111111111
    [July] => 17.77777777777778
    [November] => 12.222222222222221
    [March] => 12.777777777777777
    [December] => 11.11111111111111
    [September] => 15.0
)
</pre>

I want to sort this array on the basis of month (key)

I used ksort() function but error coming that it must be array not object.

Then I converted it to array as array($data); and then used ksort() again but still no result.

Please help my guys how to do??

share|improve this question

marked as duplicate by Mihai Iorga, Rikesh, Shankar Damodaran, trudyscousin, Rahil Wazir Apr 26 at 7:56

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
@MihaiIorga thats is array while i have stdclassobject –  user3110655 Apr 26 at 6:05
2  
So turn it into array ... use $std = json_encode($std), $std = json_decode($std, true) –  Mihai Iorga Apr 26 at 6:06
    
@MihaiIorga please check again my question –  user3110655 Apr 26 at 6:07
    
Did you read my last comment ? –  Mihai Iorga Apr 26 at 6:08
    
not clealry can you give me answer with solution. –  user3110655 Apr 26 at 6:10

2 Answers 2

You can use ksort() but you will first need to turn your object into an array.

You can do this with json_encode/json_decode

$array = json_decode( json_encode( $stdObject ), true );

ksort( $array );

foreach($array as $key => $val) {
    echo $key. '=' .$val.'<br />'
}
share|improve this answer

you should try the following code for your task:

$months=array("October" => "6.2","January" => "0.2","April" => "1.5","February" => "0.2","August" => "5.4","June" => "3.1","May" => "4.5","July" => "4.2","November" => "2.5", "March" => "0.5","December" => "0.7","September" => "6.9");

        ksort($months);

                   foreach($months as $key=>$keyvalue)//$x=>$x_value
        {
        echo "<br>".$key."=>".$keyvalue;
        }
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.