Page 1 of 1

Sort in multi-dimensional array

Posted: Sat May 25, 2002 12:30 pm
by Dust
It this exampe $coloumn in function "scmp" is undefined. How correct this problem? Or how I can sort multid. array on whole coloumn?

Code: Select all

function selectsort ($filename, $sort) {
	$this->openfile($filename);
	$lines = $this->filesї$filename];
// sort
	global $coloumn;
	$coloumn = 6;
function scmp ($a, $b){
 if ($aї$coloumn]>$bї$coloumn])
  $result = 1;
	else if($aї$coloumn]==$bї$coloumn])	
           $result = 0;
		else
		  $result = -1;
	echo " ".$aї$coloumn]."->".$coloumn;
 return ($result *(-1));
}

	usort($lines, "scmp");
//end of sort

	return $lines;

}

Posted: Sat May 25, 2002 4:55 pm
by volka
your main problem is that function scmp ($a, $b) is definied as inner function. I don't think php supports that.
But try this:

Code: Select all

<?php
class Comparator
{
   var coloumn = 0;
   function Comparator() {}
   function smcp($a, $b)
   {
      return (strcmp($aї$this->coloumn], $bї$this->coloumn])*-1);
   } 

   function openfile() ...
   function files() ...
   function selectsort ($filename, $sort) 
  { 
     $this->openfile($filename); 
     $lines = $this->filesї$filename]; 
     $this->coloumn = 6; 
     usort($lines, array(this,"scmp")); 
     return $lines; 
  }
}
?>
^ not even 'tested by compiler' ;)

Thanks, bat....

Posted: Sat May 25, 2002 5:33 pm
by Dust
PHP prefect support inner function :-)
I Solve my problem - see my bug here:

function selectsort ($filename, $sort) {
$this->openfile($filename);
$lines = $this->files[$filename];
// sort
global $coloumn;
$coloumn = 6;
function scmp ($a, $b){
global $coloumn;
if ($a[$coloumn]>$b[$coloumn])
$result = 1;
else if($a[$coloumn]==$b[$coloumn])
$result = 0;
else
$result = -1;
echo " ".$a[$coloumn]."->".$coloumn;
return ($result *(-1));
}

usort($lines, "scmp");
//end of sort

return $lines;

}


I not define $coloumn as global in new scope... :-)