Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

how to sort 2 dimensiona array in php

Posted on 2010-08-18
21
Medium Priority
?
406 Views
Last Modified: 2013-11-10
hi there,

i have put  a lot array into one array called $mPeople, now i would like to sort $mPeople by 'smoker',  any Tips?

Codes related:

//$Human is array which i got from web service.

$mPeople= array();
foreach($Human as $id=>$people) {
 $everyone = array('id'=>$people->mId,'name'=>$people->mName, 'hobby'=>$people->mHobby, 'smoker'=>$people->isSmoker);
 array_push($mPeople,$everyone);
}


thanks,

wantime
0
Comment
Question by:wantime
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 6
  • 2
21 Comments
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 33462715
Use uasort and write your own comparison function

http://www.php.net/uasort

Your comparison function would look something like

function compareArray( $a, $b ) {
     if ( $a['smoker'] < $b['smoker'] )
          return -1;
     else
          if ( $a['smoker'] > $b['smoker'] )
               return 1;

     return 0;
}

and then you would call it like so

uasort( $myArrayToSort, 'compareArray');

(all the above UNTESTED)

For future work you may want to consider this http://www.experts-exchange.com/A_316-Simplify-your-coding---string-handling-in-HTML-&-PHP.html
0
 

Author Comment

by:wantime
ID: 33462766
i have tried following codes, but it doesn|t work, i just get error
Warning: usort() [function.usort]: Invalid comparison function...

public function cmp($a, $b) {
 if (($a[3] == $b[3]) ) {
         return 0;
 } else if ($a[3]){
          return 1;
 } else {
        return -1;
 }
}

 usort($mPeople, "cmp");
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:wantime
ID: 33462785
@bportlock

thanks. i  have just readed your comment..

what i want to say is that the $a['smoker']  is a boolean type.
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 33463040
In that case change the comparison function

function compareArray( $a, $b ) {
     if ( $a['smoker'] && !$b['smoker'] )
          return -1;
     else
          if ( !$a['smoker'] && $b['smoker'] )
               return 1;

     return 0;
}
0
 

Author Comment

by:wantime
ID: 33464684
i used

uasort( $mPeople, 'compareArray');

but got the error:

uasort() [function.uasort]: Invalid comparison function...
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 33466841
Check for either a mis-spelling of "compareArray" and that the function is within the scope of the uasort. I usually ensure that functions are declared higher up the program than their point of use.

Also are you doing this in "ordinary code" or in a class? The syntax is different within a class if the comparison function is a member function. It would be

uasort( $mPeople, array( $this, 'compareArray') );

If all else fails, post the code here
0
 

Author Comment

by:wantime
ID: 33472660
the method uasort( $mPeople, 'compareArray'); cause error

"uasort() [function.uasort]: Invalid comparison function...", and when i use

method "uasort( $mPeople, array( $this, 'compareArray') );", i get errorinfo "Application Error"  on the website.

i use the method in one class, the structure looks like following:






<?php
class Model_Person
{

public function compareArray( $a, $b ) {
if ( $a['smoker'] && !$b['smoker'] )
return -1;
else
if ( !$a['smoker'] && $b['smoker'] )
return 1;

return 0;
}

//comment (removed)

public function getInfoFromWS() {

$mPeople = array();

... //get $Human from Web Service

foreach($Human as $id=>$people) {

$everyone = array('id'=>$people->mId,'name'=>$people->mName, 'hobby'=>$people->mHobby, 'smoker'=>$people->isSmoker);
array_push($mPeople,$everyone);
}
//uasort($mPeople, 'compareArray');
uasort( $mPeople, array( $this, 'compareArray') );

}

return $mPeople;
}


}

?>

Open in new window

0
 
LVL 34

Accepted Solution

by:
Beverley Portlock earned 2000 total points
ID: 33472947
I modified your code slightly for testing purposes, but it seems OK to me, it certainly runs OK. The modified code is below. Try running it because it works here. If it does not work for you then your problem isn't uasort() it is something else.

Are you on an older version of PHP? Run <?php phpinfo(); ?> to check


<?php
class Model_Person
{
      
   public function compareArray( $a, $b ) {
     if ( $a['smoker'] && !$b['smoker'] )
          return -1;
     else
          if ( !$a['smoker'] && $b['smoker'] )
               return 1;

     return 0;
   }
   
    //comment (removed)
   
    public function getInfoFromWS() {
       
                  $mPeople = array(
                                      array( 'id' => '123', 'name' => 'fred', 'hobby' => 'swimming', 'smoker' => true ),
                                      array( 'id' => '456', 'name' => 'john', 'hobby' => 'runnihg', 'smoker' => false ),
                                      array( 'id' => '789', 'name' => 'mary', 'hobby' => 'horseriding', 'smoker' => true ),
                                      array( 'id' => '555', 'name' => 'bert', 'hobby' => 'flying', 'smoker' => fa ),
                                      array( 'id' => '111', 'name' => 'eddy', 'hobby' => 'reading', 'smoker' => true ),
                                  );
/*                  
                  //... //get $Human from Web Service
            
            foreach($Human as $id=>$people) {
                  
                        $everyone = array('id'=>$people->mId,'name'=>$people->mName, 'hobby'=>$people->mHobby, 'smoker'=>$people->isSmoker);
                        array_push($mPeople,$everyone);
                  }
               //uasort($mPeople, 'compareArray');
*/
           
           uasort( $mPeople, array( $this, 'compareArray') );

        
               
        return $mPeople;
    }


}


$mp = new Model_Person();
print_r( $mp->getInfoFromWS() );
?>

Open in new window

0
 

Author Comment

by:wantime
ID: 33474970
thanks bportlock.
0
 
LVL 9

Expert Comment

by:Snarfles
ID: 33475989
I object to this being deleted on behalf of bportlock who has obviously put in a lot of effort to solve this. If there is some code that shouldn't be public it should be edited out by a mod but the rest of the question should remain and bportlock should get the points.
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 33479994

  :-O

Very kind of you snarfles. I'm speechless and that doesn't happen often.


0
 

Author Comment

by:wantime
ID: 33482641
if one can delete the comment in both codes, that would be nice.
0
 

Author Comment

by:wantime
ID: 33485452
who is the mod and how can i contact with him? i have no right to modify the comment.
0
 
LVL 9

Expert Comment

by:Snarfles
ID: 33495431
Hi Vee Mod

Thanks for your comment. I could have sworn that I clicked an object button and that I filled in a reason for doing so. That being said I've never had a reason to object before so I guess I could have stuffed it up.  

At any rate, this isn't my question, nor am I the person who answered it. I was just monitoring it to learn from it and thought that bportlock deserved the points.

Do you now want me to click 'request attention' or is it fine from now on?

Thanks

Snarfles
0
 

Author Comment

by:wantime
ID: 33498638
hi all,

i have already click the 'request attention' and wrote the reason there. I just wait for mod to edit out the codes.

thanks,

wantime
0
 

Author Comment

by:wantime
ID: 33530240
thanks you for your work!

btw, i never refuse to award points to the Experts, i just wanted to correct the mistake at first.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this. Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it i…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses

609 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question