Jump to content

Php Arrays - Sort etc. - Low Difficulty - Help Needed Please.


johnsmith153

Recommended Posts

I have data stored as such in arrays (php)

 

$value1[1]="27";

$value2[1]="Dave";

 

$value1[2]="33";

$value2[2]="Paul";

 

$value1[3]="18";

$value2[3]="John";

 

Say that $value1 is Age, and $value2 is their Name.

 

I need to sort them in order (which is pretty easy for one array) - but I must keep each matching $value1 and $value2 together

 

Ie: I expect to return: (ranking in order of age, youngest first)

 

18, John

27, Dave

33, Paul

 

If I sort the $value1 array, then I will not be able to match the age up with the $value2 (Name) array.

 

I could store the values differently in the first place if I need to. Maybe I was wrong to store them how I have.

 

If someone could provide the code for the above example I could transfer it to the actual code I am working on.

 

??

 

Thanks in advance.

function sort_nameage($a, $b)

{

    if ($a['age'] == $b['age']) {

return 0;

}

       return ($a['age] < $b['age']) ? -1 : 1;

}

 

$somearray[] = array("age" => 27, "name" => "Dave");

$somearray[] = array("age" => 33, "name" =>"Paul");

$somearray[] = array("age" => 18, "name" => "John");

usort($somearray, 'sort_nameage');

Woops:

 

function sort_nameage($a, $b)

{

      if ($a['age'] == $b['age']) {

        return 0;

      }

        return ($a['age'] < $b['age']) ? -1 : 1;

}

 

$somearray[] = array("age" => 27, "name" => "Dave");

$somearray[] = array("age" => 33, "name" =>"Paul");

$somearray[] = array("age" => 18, "name" => "John");

usort($somearray, 'sort_nameage');

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.