0

So this question is probably pretty basic.

I am wanting to create an array from selected elements from a SQL table.

I am currently using:

$rcount = mysql_num_rows($result);

for ($j = 0; $j <= $rcount; $j++)
{
    $row = mysql_fetch_row($result);
    $patients = array($row[0] => $row[2]);
}

I would like this to return an array like this:

$patients = (bob=>1, sam=>2, john=>3, etc...)

Unfortunately, in its current form, this code is either copying nothing to the array or only copying the last element.

1
  • I dont really understand what you want to do here, with in the for loop, you are not using the variable j. Please make it more clear, Commented Jan 13, 2011 at 2:28

3 Answers 3

2

Try this instead.

$patients = array();
while ($row = mysql_fetch_row($result)) {
    $patients[$row[0]] = $row[2];
}

If it doesn't work, there's something wrong with your query.

Sign up to request clarification or add additional context in comments.

1 Comment

This is much closer to what I want, but I'm trying to avoid having arrays within arrays. Is there someway to modify this so that I don't have Array ( [0] => Array ( [bob] => 5 ) [1] => Array ( [fred] => 1 )), but rather Array([bob]=>5, [fred]=>1)? Thanks.
0

you can use print_r()

here is an example

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

more here http://php.net/manual/en/function.print-r.php

1 Comment

im not sure I understand, won't this just print the elements of the array after I've created it. Furthermore, as I understand it, this wouldn't allow me to select only certain elements from the table to be put in the array.
0

How about this :

while($row = mysql_fetch_assoc($result)){
        $arr_row=array();
        $count=0;
        while ($count < mysql_num_fields($result)) {       
            $col = mysql_fetch_field($result, $count);   
            $arr_row[$col -> $count] = $row[$col -> $count];           
            $count++;
 }   

But I not sure if this is what you are looking for, just guessing .. ount

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.