Multi Dimensional Arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
oQEDo
Forum Commoner
Posts: 43
Joined: Thu Feb 20, 2003 11:08 am
Location: UK

Multi Dimensional Arrays

Post by oQEDo »

Kind of new to PHP, have moved from ASP.
My question is I am trying to put the results of a query on a mySQL database into a multi dimensional array but having no success!

My Code.....

<?php
require ('conn.php');

$MYSQL = mysql_query("SELECT * FROM Cost order by CostID Asc");
$RS = mysql_fetch_array($MYSQL,MYSQL_ASSOC);

$i = 0;
while ($RS = mysql_fetch_array($MYSQL,MYSQL_ASSOC))
{
$CostArray = array(
i => array($RS{'CostID'},$RS{'CostName'},$RS{'CostType'},$RS{'CostPrice'})
);
$i++;
}

print_r($CostArray);
?>

I am trying to create an array so I can call each element as:
$CostArray[0][0]
$CostArray[0][1] etc...

Please help.

Tx
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post by Stoker »

if you want it stored as numericals, after the query do

$mydata = array();
while ($row = mysql_fetch_row($RS)) $mydata[] = $row;

then access it as you indicated.

I find it 'prettier' to use associative naming, use this

$mydata = array();
while ($row = mysql_fetch_assoc($RS)) $mydata[] = $row;

and access with
$mydata[rownumber]['columnname']
e.g. $mydata[4]['CostId'] for the CostId value of record 5
User avatar
oQEDo
Forum Commoner
Posts: 43
Joined: Thu Feb 20, 2003 11:08 am
Location: UK

Thanks

Post by oQEDo »

:D So easy!
Thanks very much, I have been staring at that for ages. I knew that there must be an easy way to do it but i'm a newbie.

Appreciated
Post Reply