Jump to content

**SOLVED**Fill an array


craygo

Recommended Posts

I have a table and I want to put a couple fields into an array. I would like to query the table with my parameters then fill the array the keys will be one field and the values will be another field. I tried this but it is not correct

[code]<?php
$accounts = array();
$sql = "SELECT * FROM tokayacct";
  $res = mysql_query($sql) or die (mysql_error());
    while($r=mysql_fetch_assoc($res)){
$accounts[0] = $r['account_num'];
$accounts[1] = $r['meter_num'];
}
?>[/code]

thanks guys

Ray
Link to comment
https://forums.phpfreaks.com/topic/23699-solvedfill-an-array/
Share on other sites

ok so account_num , meter_num , are in your table. You want this stored in an array.. maybe store it by id and put another array in there.

you could use something like:
[code]
<?php

$accounts = array();
$sql = "SELECT * FROM tokayacct";
  $res = mysql_query($sql) or die (mysql_error());
    while($r=mysql_fetch_assoc($res)){
    $accounts[$r[id]] = array($r['account_num'], $r['meter_num']);
}

?>
[/code]

something like that might work..
Link to comment
https://forums.phpfreaks.com/topic/23699-solvedfill-an-array/#findComment-107585
Share on other sites

The reason the OP's original code does not work is that the OP is constantly overlaying the first and second elements in the array.

Another way of doing this would be:
[code]<?php
$accounts = array();
$sql = "SELECT * FROM tokayacct";
  $res = mysql_query($sql) or die (mysql_error());
    while($r=mysql_fetch_assoc($res)){
    $accounts[$r['account_num']] = $r['meter_num'];
}?>[/code]

Which builds an array that is keyed by the account_number.

Ken
Link to comment
https://forums.phpfreaks.com/topic/23699-solvedfill-an-array/#findComment-107587
Share on other sites

Make a 2 dimensional array:
[code]<?php
$accounts = array();
$currow = 0; //initialize
$sql = "SELECT * FROM tokayacct";
  $res = mysql_query($sql) or die (mysql_error());
    while($r=mysql_fetch_assoc($res)){
        //2 dimensional array notation used below
        $accounts[$currow]['account_num'] = $r['account_num'];
        $accounts[$currow]['meter_num'] = $r['meter_num'];
        //add other fields you want to store here
        $currow++; //increment first array index
    }
?>[/code]
Link to comment
https://forums.phpfreaks.com/topic/23699-solvedfill-an-array/#findComment-107595
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.