views:

52

answers:

3
+2  Q: 

2D array in PHP

how can I store $result value in a 2d array. here my code-

$sql="SELECT a.userId, b.name, b.dob FROM tbltree a INNER JOIN tblprofile b ON a.userId = b.userId WHERE a.superId ='$uid'";
$result=mysql_query($sql,$link)or die(mysql_error());

2d array having three columns-userId | name | dob

+4  A: 

Something like this:

$sql = "..."
$result = mysql_query(...) ...;

$result_array = array();
while($row = mysql_fetch_assoc($result)) {
    $result_array[] = $row;
}

That will give you:

$result_array[0] = array('key1' => 'val1', 'key2' => 'val2', ...);
$result_array[1] = array('key1' => 'val1', 'key2' => 'val2', ...);
$result_array[2] = etc...

If you don't want an associate array for the sub-array, there's other fetch modes as well

Marc B
@marc okie, it means if i have to access first row, i can access like `result_array[0][userId] OR result_array[0][name]`. Is it?
nectar
It'd be a regular multidimensional array, which in PHP is just an array of arrays. So... $result_array[1]['key1'] would fetch the value associated with 'key1' from the 2nd entry in the main array. You can add as many dimensions as you want, but after 3 or 4, things get nasty to keep straight in your head.
Marc B
@nectar `$result_array[0]['userId']` to be correct, but most likely you'll never address array variables like this because arrays intended to be iterated using `foreach()` operator
Col. Shrapnel
A: 
$sql = "SELECT a.userId, b.name, b.dob FROM tbltree a INNER JOIN tblprofile b ON a.userId = b.userId WHERE a.superId ='$uid' LIMIT 1";

Then we use mysql_fetch-assoc to collect a row

if(false != ($resource = mysql_query($sql)))
{
    $result = mysql_fetch_assoc($resource);
    // Dont use a while here as we only want to iterate 1 row.
}

echo $result['name'];

Also added "LIMIT 1" to your query

RobertPitt
A: 

you need to run in while loop on $result

while ($row = mysql_fetch_assoc($result)) {
    $array[] =  $row;
}

more details: http://php.net/manual/en/function.mysql-fetch-assoc.php

Haim Evgi