Page 1 of 1
an array of objects?
Posted: Wed Nov 27, 2002 8:40 pm
by Sevengraff
Im trying to make an array of objects, and its not working. I want to use it so that i can load some mysql data into it, and then sort it for output. but when i try to do it, everything prints out as object->element name. its strange that it doesnt give an error.
Posted: Thu Nov 28, 2002 12:36 am
by volka
Code: Select all
<?php
...
$query = 'SELECT id from tablename';
$result = mysql_query($query, $conn);
$objs = array();
while( $row = mysql_fetch_object($result) )
$objsї] = $row;
...
for ($i=0; $i!=count($objs); $i++)
echo $objsї$i]->id, '<br/>';
?>
although I like the array-versions
mysql_fetch_row and
mysql_fetch_assoc more

Posted: Wed Dec 04, 2002 8:41 pm
by Sevengraff
hmm, i should check my email for replies more often...
I tried using the example posted above, and modified it to work like i wanted, but it didn't give the desired results.
I am trying to re-create something i've done in my C++ class. There i had to load data from a file into an array of structs and use a swap fuction to sort the data in order. i cant seem to get the same thing in PHP.
how would i do this:
- get data from mysql table (select * from users where id=$id is what i will use)
- load into array (or maybe some other grouping).
- sort it (i've allready writen a function to do this)
- print in descending order
thats sorta the algorithm.
Posted: Wed Dec 04, 2002 9:45 pm
by volka
e.g.
Code: Select all
<?php
function descendingLastNameSort($a, $b)
{
return -strcmp($a['lastname'], $b['lastname']);
}
$conn = mysql_select(....);
mysql_select_db(..., $conn);
$query = 'SELECT * FROM users WHERE id='.$id; // having a field lastname
$result = mysql_query($query, $conn);
$arr = array();
while($row = mysql_fetch_assoc($result))
$arr[] = $row;
$arr = usort($arr, 'descendingLastNameSort');
echo '<table>';
foreach($arr as $entry)
{
echo '<tr>';
foreach($entry as $field)
echo '<td>', $field, '</td>';
echo '</tr>';
}
echo '</table>';
?>
but much simpler and probably faster when done by
Code: Select all
<?php
$conn = mysql_select(....);
mysql_select_db(..., $conn);
$query = 'SELECT * FROM users WHERE id='.$id.' ORDER BY lastname DESC';
$result = mysql_query($query, $conn);
echo '<table>';
while($row = mysql_fetch_assoc($result))
{
echo '<tr>';
foreach($row as $field)
echo '<td>', $field, '</td>';
echo '</tr>';
}
echo '</table>';
?>
(both script not even tested by compiler

)
Posted: Wed Dec 04, 2002 10:07 pm
by Sevengraff
oh my, i wasnt aware of "ORDER BY lastname DESC", that makes things a lot easier!
Posted: Wed Dec 04, 2002 10:33 pm
by volka