Log in

View Full Version : Resolved array_push / sort



ggalan
10-26-2011, 06:13 PM
running into a weird problem. i have an array reading from a dB and would like to add manually to this list then sort()
but sort seems to only apply to the while loop, why? how can i fix this?
as always any help would be appreciated, thanks.


$rows = array();
array_push($rows, 'b new item');// this gets left out
while ($row0 = mysql_fetch_array($result0))
{
array_push($rows, $row0[1]);
}
sort($rows);// only sorts the items in the while loop
foreach($rows as $r) {
$string .= "<li><a href='#'>" . $r . "</a></li>" . "\n";
}
echo $string;

traq
10-26-2011, 07:16 PM
works for me (the initial value is included, and sorted). What does var_dump($rows) (after the while loop) give you?

ggalan
10-26-2011, 11:10 PM
var dump out puts with the index's but 'b new item' should fall after items that start with 'a' but it doesnt. it lists as the last


{ [0]=> string(11) "Alchemy" [1]=> string(12) "Alchemy P" [2]=> string(7) "Carezza" [3]=> string(11) "Eco" [4]=> string(6) "Fusion" [5]=> string(5) "Helio" [6]=> string(12) "b new fabric" }

djr33
10-26-2011, 11:16 PM
I've never seen a need to use array_push(). I just use this syntax (as mentioned on php.net for the array_push() description as well).


$array[] = $newitem; //add $newitem to end of $array
I've never had any problems like you are describing when I use this method. But I don't know about array_push(). I think it should work the same way, but I don't know.

The only thing I can see is that maybe array_push() never adds the item because array_push() only works on an array that already has some contents. I don't know if that is true. Try using var_dump() or print_r() BEFORE the while loop as well. If it wasn't added then, then it won't be there later. I don't think the while loop is erasing it.

ggalan
10-26-2011, 11:28 PM
i see, that gave me the same result.
heres my trimmed down flow


$query0 = "SELECT * FROM fabrics WHERE subCategoryID='$qs' AND discontinued=0 ORDER BY trim(fabricName)";
$result0 = mysql_query($query0) or die (mysql_error());

$rows[] = 'b new fabric';
while ($row0 = mysql_fetch_array($result0))
{
$rows[] = $row0[1];
}
sort($rows);
//var_dump($rows);
$string = "<ul class='sub-menu sub-menu-home'>" . "\n";
foreach($rows as $r) {
$r = ucwords($r);
$string .= "<li><a href='#'>" . $r . "</a></li>" . "\n";

}
$string .= "</ul>";
echo $string;

traq
10-26-2011, 11:58 PM
ah. use natcasesort() (http://us.php.net/manual/en/function.natcasesort.php) instead.

ggalan
10-27-2011, 12:00 AM
awesome! thanks