Jump to content


Photo

sorting arrays


  • Please log in to reply
4 replies to this topic

#1 ToonMariner

ToonMariner
  • Members
  • PipPipPip
  • Advanced Member
  • 3,342 posts
  • LocationNewcastle upon Tyne, UK

Posted 12 July 2006 - 09:30 AM

Sure this is easy BUT i just can't find the solution.

OK i have 2 arrays.

arr1 = 5,7,1,4,6,3,2;

arr2 = 3,5,4,7;

I want to use the order of values in arr1 to sort the order of arr2.

the result would yield:-

arr2 = 5,7,4,3

any help appreciated - and I'm sure I will be wearing a dunce hat when someone shows how simple it is!!!!!

Brain just not working today....
follow me on twitter @PHPsycho

#2 GingerRobot

GingerRobot
  • Staff Alumni
  • Advanced Member
  • 4,086 posts
  • LocationUK

Posted 12 July 2006 - 09:47 AM

this is what ive got so far:

<?php
$arr1 = array('5','7','1','4','6','3','2');
$arr2 = array('3','5','4','7');

foreach($arr2 as $check)
{
  $i = 0;
  while($i < count($arr1))
  {
      if($check == $arr1[$i]){
	  $newarray[$i] = $check;
	}
	$i++;
}
}
ksort($newarray);
print_r($newarray);
?>

The output from that is:
Array ( [0] => 5 [1] => 7 [3] => 4 [5] => 3 )

Im just trying to figure out how to re-do the keys so you have 0,1,2,3 as keys instead. Im sure theres a function somewhere...

#3 GingerRobot

GingerRobot
  • Staff Alumni
  • Advanced Member
  • 4,086 posts
  • LocationUK

Posted 12 July 2006 - 09:53 AM

might be an easier way, but i created a second array with keys and used array_combine:

<?php
$arr1 = array('5','7','1','4','6','3','2');
$arr2 = array('3','5','4','7');

foreach($arr2 as $check)
{
  $i = 0;
  while($i < count($arr1))
  {
      if($check == $arr1[$i]){
	  $newarray[$i] = $check;
	}
	$i++;
}
}
ksort($newarray);
$i=0;
while($i< count($newarray)){
  $keys[$i]= $i;
  $i++;
}
$newarray = array_combine ($keys, $newarray);
print_r($newarray);

?>


#4 ToonMariner

ToonMariner
  • Members
  • PipPipPip
  • Advanced Member
  • 3,342 posts
  • LocationNewcastle upon Tyne, UK

Posted 12 July 2006 - 10:02 AM

You're a gentleman and a scholar....

cheers mate.
follow me on twitter @PHPsycho

#5 GingerRobot

GingerRobot
  • Staff Alumni
  • Advanced Member
  • 4,086 posts
  • LocationUK

Posted 12 July 2006 - 10:03 AM

No problem, it was a nice thing to solve :)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users