tonio94
tonio94

Reputation: 510

How to create and fill a three dimensional array

From a csv file I want to create and fill a three dimensional array that must match this example :

$line_chart_data=array(
                array(
                    array("Jan",48.25),
                    array("Feb",238.75),
                    array("Mar",95.50)),
                );

The goal is to create a readable array for a php chart library.

This is my code :

function createChartData()
{
    $timestamp = 0;
    $keys = array();
    if (($handle = fopen("file.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            $timestamp++;
            $keys[] = array($timestamp, $data[1]);
            }
        }
        fclose($handle);
    return $keys;
}

Result is :

Array ( [0] => Array ( [0] => 1 [1] => 3243259 ) [1] => Array ( [0] => 2 [1] => 3243200 ) [2] => Array ( [0] => 3 [1] => 3243100 ) )  

It misses one array (second one in the example). I don't know how and where to include it in my code.

Upvotes: 0

Views: 777

Answers (1)

Don't Panic
Don't Panic

Reputation: 41810

If your function is already returning

array(
    array("Jan",48.25),
    array("Feb",238.75),
    array("Mar",95.50)
)

and you just need one more array around the output to get the three-dimensional structure you need for your chart, there are a couple of different ways to do it.


One is to add the extra array layer as you append rows to the result, so instead of

$keys[] = array($timestamp, $data[1]);

you can use

$keys[][0] = array($timestamp, $data[1]);
//      ^ second level

Another is to just wrap the the output in an array before you return it, so return [$keys]; instead of return $keys;. (In older versions of PHP it would be return array($keys);)

Upvotes: 1

Related Questions