Jump to content

[SOLVED] array sort not working correctly


EchoFool

Recommended Posts

Im trying to get a script to select the lowest ID in an array based on which one has the lowest value related to it and then when there are two with equally low values it picks the lowet position in the array.

 

At the momeht how ever it just picks the same one every time regardless of value.

 

heres what i have:

<?php
$Get = mysql_query("SELECT Name,StateID FROM state WHERE Ended != '1' ORDER BY StateID ASC")
	Or die(mysql_error());
	$State = array();
		While($row = mysql_fetch_assoc($Get)){
			$StateID = $row['StateID'];
			$worth = 0;
			$SELECT = mysql_query("SELECT (Population*1000) AS Worth
						FROM city WHERE StateID='{$row['StateID']}'")
							Or die(mysql_error());
	If(mysql_num_rows($SELECT)>0){
		While($row2 = mysql_fetch_assoc($SELECT)){
		$worth = $worth + $row2['Worth'];
			}
		}
	$State[] = $worth; 
	unset($worth);
	}
	$Choice = asort($State);

print_r($State);
Echo '<br><br>';
Echo $Choice;
?>

 

Heres an example of the echo:

Array ( [ 3 ] => 0 [ 2 ] => 0 [ 1 ] => 20000 [ 0 ] => 20000 )

 

1

 

As you can see it should have been choosing between position 2 =>0 and 3 =>0. And because these are equal as 2 is the lowest position in the array it should have picked 2 but it picks 1 every time. But 1 has a value of 20000 and is clearly not the lowest so I don't know why its going wrong.

 

Hope you can help.

Link to comment
Share on other sites

the reason it returns 1 for $Choice every time, is because asort() returns TRUE or FALSE.

 

Try this code:

 

<?php
$Get = mysql_query("SELECT Name,StateID FROM state WHERE Ended != '1' ORDER BY StateID ASC") Or die(mysql_error());
$State = array ();
while ($row = mysql_fetch_assoc($Get)) {
  $StateID = $row['StateID'];
  $worth = 0;
  $SELECT = mysql_query("SELECT (Population*1000) AS Worth
                     FROM mayor_city WHERE StateID='{$row['StateID']}'") or die(mysql_error());
  if (mysql_num_rows($SELECT) > 0) {
    while ($row2 = mysql_fetch_assoc($SELECT)) {
      $worth = $worth + $row2['Worth'];
    }
  }
  $State[] = $worth;
  unset ($worth);
}
asort($State);  //Sorts it
$Choices = array_keys($State,$State[0]); //Finds all keys with the lowest value
sort($Choices); //Sorts those keys
$Choice = $Choices[0]; //Get's the lowest key
  
print_r($State);
echo '<br><br>';
echo $Choice;
?>

Link to comment
Share on other sites

Ok tried that and got this:

 

<?php
asort($State);  //Sorts it
$Choices = array_keys($State,$State[0]); //Finds all keys with the lowest value
sort($Choices); //Sorts those keys
$Choice = $Choices[0]; //Get's the lowest key


print_r($State);
echo '<br><br>';
echo $Choice;
?>

 

and got:

Array ( [3] => 0 [2] => 0 [ 0 ] => 20000 [1] => 20000 )

 

0

 

Is it returning the value or the array position because i need the position number in this particular case it would be [2]. ?

Link to comment
Share on other sites

problem is in rhodesa's code array_keys will return all the keys with value of first value from asort (all the ones with value "0" in this instance) but the returned array is itself re-indexed. 

 

$array = array(20000,20000,0,0); // example array
$temp = $array;  // make a temp array to sort, to preserve original array
sort($temp); // sort $temp to have lowest val first
$key = array_search($temp[0], $array); // search $array using first val in $temp, returning first key found
$val = $array[$key]; // get the value using the key found
echo "$key => $val"; // output: 2 => 0

Link to comment
Share on other sites

another way...but Crayon Violent's is probably faster

 

<?php
$State = array(
  0 => 20000,
  1 => 20000,
  2 => 0,
  3 => 0,
);
$ChoiceKey = false;
$ChoiceValue = false;
foreach($State as $Key=>$Value){
  if($ChoiceValue === false || $Value < $ChoiceValue || ($Value == $ChoiceValue && $Key < $ChoiceKey)){
    $ChoiceKey = $Key;
    $ChoiceValue = $Value;
  }
}

print_r($State);
echo '<br><br>';
echo $ChoiceKey;
?>

Link to comment
Share on other sites

I like sasa's option the best because it's less code, though I'm fairly certain it's not any faster than mine.  Also, it's bugged.  I fixed it:

 

<?php
$State = array(
  0 => 20000,
  1 => 20000,
  2 => 0,
  3 => 0,
);
$ChoiceKey = array_search(min($State), $State);
print_r($State);
echo '<br><br>';
echo $ChoiceKey;
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.