Jump to content

Sorting Arrays


moon 111

Recommended Posts

No. That won't help me. I already tried that.

 

Example:

 

$title = array('Hello!', 'Title #2', 'A title!');
$description = array('message', 'blah', 'text');

 

If I sort $title and $description seperately it will only mess it up. I want to sort $title and then apply the same thing to $description without mixing up the values.

 

What I want the arrays to look like after the sort is:

 

$title = array('A title!', 'Title #2', 'Hello!');
$description = array('text', 'blah', 'message');

 

Get it?

Link to comment
https://forums.phpfreaks.com/topic/99949-sorting-arrays/#findComment-511074
Share on other sites

You can stick them in a multidimensional array and use a user defined sort function.

 

<?php
$title = array('Hello!', 'Title #2', 'A title!');
$description = array('message', 'blah', 'text');
$array= array();
for($x=0;$x<count($title);$x++){
   $array[$x]['title'] = $title[$x];
   $array[$x]['description'] = $description[$x];
}
function mysort($a,$b){
   return strcmp($a['title'],$b['title']);
}
echo '<pre>'.print_r($array,1).'</pre>';
usort($array,'mysort');
echo '<pre>'.print_r($array,1).'</pre>';
?>

 

The returned array might not quite be what you were expecting, but it may actually be more useful.

 

See: http://www.php.net/usort

Link to comment
https://forums.phpfreaks.com/topic/99949-sorting-arrays/#findComment-511081
Share on other sites

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.