0

I am using php and I want to be able place two fields from a query into an array.

I currently have the following which works well:

$sql = "SELECT * FROM table;";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$array[]=$row['field1'];
}

But I can't seem to work out how to read two fields:

    $array[][]=$row['field1'] in the first, and  $row['field2'] in the second;

So I should get:

$array [0][0] as field1
and
$array [0][1] as field2
Jonny C
  • 1,943
  • 3
  • 20
  • 36
RGriffiths
  • 5,722
  • 18
  • 72
  • 120
  • I think you want to do this: `$array[$row["field1"]][] = $row["field2"];` – Rizier123 May 01 '15 at 12:38
  • no idea - that is why I am asking for help. I want them separate in the array – RGriffiths May 01 '15 at 12:39
  • Changed my comment, see my updated one ^ – Rizier123 May 01 '15 at 12:40
  • Do you want "field1" as $array[0] and "field2" as $array[1]? – bstakes May 01 '15 at 12:41
  • Edited the question for clarity @Rizier123 I am afraid that did not work. – RGriffiths May 01 '15 at 12:45
  • Please, [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard May 01 '15 at 12:47

1 Answers1

0
$array = array ();
while(($row = mysql_fetch_array($result))
{
    $subarray = array ();
    $subarray[] = $row['field1'];
    $subarray[] = $row['field2'];
    $array[]= $subarray;
}

// more concisely:
$array = array ();
while(($row = mysql_fetch_array($result))
{
    $array[] = array (
        $row['field1'],
        $row['field2']
    );
}    
bstakes
  • 1,898
  • 14
  • 12