Home > Software design >  Iterate & assign 2d-array to another 2d-array (php)
Iterate & assign 2d-array to another 2d-array (php)

Time:11-29

I am a bootcamp(php) chick from Japan.

I am trying to display a bubble chart through CanvasJS. from CSV file.
I have done with reading the CSV data into an array**($dataArray).**
However, the CanvasJS shows example only with putting all values manually,
https://canvasjs.com/php-charts/bubble-chart/
but I want to make it loop.(if I put a CSV file, then making a chart automatically)
I have searched how to loop on the web for a couple of days, but couldn't figure it out.

Here is a 2d-array**($dataArray)** from CSV file;

Array
(
    [0] => Array
        (
            [0] => Chrysler
            [1] => USA
            [2] => 291
            [3] => 32970
            [4] => 15.2
            [5] => 11.8
...
    [23] => Array
        (
            [0] => Nissan
            [1] => Japan
            [2] => 251
            [3] => 36314
            [4] => -4.2
            [5] => 2.9
        )

)

and I want it to loop & assign values to another 2d-array**($dataPoints)** so that 'CanvasJS' can render a bubble chart.

$dataPoints = array(
  array('name' => $dataArray[0][0], 'x' => $dataArray[0][2], 'y' => $dataArray[0][3], 'z' => $dataArray[0][5]),
  array('name' => $dataArray[1][0], 'x' => $dataArray[1][2], 'y' => $dataArray[1][3], 'z' => $dataArray[1][5]),
  array('name' => $dataArray[2][0], 'x' => $dataArray[2][2], 'y' => $dataArray[2][3], 'z' => $dataArray[2][5]),
  array('name' => $dataArray[3][0], 'x' => $dataArray[3][2], 'y' => $dataArray[3][3], 'z' => $dataArray[3][5]),
  array('name' => $dataArray[4][0], 'x' => $dataArray[4][2], 'y' => $dataArray[4][3], 'z' => $dataArray[4][5]),
  ...

As you can see, $dataPoints array includes 4 keys(?), and it should be like,

'name' => &dataArray[$i][0]
'x' => &dataArray[$i][2]
'y' => &dataArray[$i][3]
'z' => &dataArray[$i][5]

Thank you for your help!!

During a couple of days,

  • I have searched how to iterate to read 2d-array to assign another 2d-array in php.
  • inquired to CanvasJS, but no response.

CodePudding user response:

Do you mean a loop like this?

    $dataPoints = [];
    foreach($dataArray as $row) {
        $dataPoints[] = [
            'name' => $row[0],
            'x' => $row[2],
            'y' => $row[3],
            'z' => $row[5],
        ];
    }
  • Related