0

I have a mysql table that has data in it that I need to use in a more basic format.

There is ID number, Date, oil, gas and electric values.

I can do a mysql_fetch_array which brings back all the values I need but I need to view them in a format for use with a javascript chart. They need to be in the format:

$data = array(array("6/22/2009",425.32),array("6/8/2009",424.84),array("5/26/2009",417.23),array("5/11/2009",390));

As you can see I need the date and the oil values. Then I need to create another array with the date and electric values and finally the data and the gas values.

I'm not sure how to get the data from the mysql_fetch_array and add it to the array as shown above. Can anyone help?

1
  • can you post your code? Commented Mar 12, 2013 at 10:16

4 Answers 4

2

You can just append it via the [] syntax:

$data = array('oil' => array(), 'gas' => array(), 'electric' => array());
while ($row = mysql_fetch_assoc($result)) {
    $data['oil'][$row['date']] = $row['oil'];
}

This assumes that the dates selected are unique as well.


By the way, you should avoid using mysql_* functions in new code.

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

Comments

1

You need to use a 'numerical array':

    $result = mysql_query(" SELECT date, oil FROM energyprices");
    $i = 0;
    while($row = mysql_fetch_array($result, MYSQL_NUM))
    {
         $oil[$i] = array($row[0], $row[1]);
         $i++;
    }

Correct me if I haven't understood your question and I'll edit my answer accordingly.

Comments

0

Try this..

$finalArray=array();
while ($row = mysql_fetch_array($result)) 
{ 
    $data=array();
    $data[] = $row['date'];
    $data[] = $row['oil'];
    $finalArray[]=$data;
}
print_r($finalArray); //This will print your values in required fromat.

Comments

0

Thanks for your help. I have amended my code to read this:

$oil = array('oil' => array());
$result=mysql_query(" SELECT * FROM energyprices");
while ($row = mysql_fetch_assoc($result)) {
$oil[$row['pDate']]['oil'] = $row['oil'];
}

When I print_r the data it looks like this:

Array ( [oil] => Array ( ) [2004-01-01] => Array ( [oil] => 29.73 ) [2004-01-02] => Array ( [oil] => 29.73 ));

The format I need it in is:

$oil = array(
array("6/22/2009",425.32),
array("6/8/2009",424.84),
array("5/26/2009",417.23));

Thank you!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.