I'm creating a class function which accepts a mysql query result and returns a multidimensional array where the first array pointer is the table column and the second pointer is a numeric indicator of its position in the MySQL data.
Eg the table has the following columns:
Groupname
Groupid
Groupurl
And the way I want to call this is:
$arrayname[groupname][1];
I have formed 2 arrays already which are:
$colnames
which contains all columns from the specific mysql query and
$$colname
which is a variable variable of the column name containing all the data in each column. Eg: $groupurl
is an array with all the data from that column.
I can't seem to get a loop to join the arrays as a multidimensional object and while I can manually do this for a specific table, it's a class function, and the variable variable part is breaking me =\
================ Thanks to IMSoP who gave me the idea, the solution is ==================
$result in the function is a successful MySQL Query on a table.
function tableAsMatrix($result)
{
//declare $results as array for use in loop
$results = array();
//this gets all the col names and sets them as $colnames[]
while( $cols = $result->fetch_field() )
{
$colnames[] = $cols->name;
}
//this loops through and assigns all cols as multidimensional $results[colname][id]
foreach ($colnames as $fields)
{
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
foreach($colnames as $field)
{
$results[$field][] = $row[$field];
}
}
}
//return to object
return $results;
}
$$colname
come from? Why can you not simply populate$return[$colname]
as you go along? – IMSoP Mar 10 '13 at 21:52mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial. – Ja͢ck Mar 11 '13 at 10:18