Reputation: 139
Using PHPGraphlib for a project.
The following adds data to the graph. The array values will be the y-axis value.
$graph->addData(array(100,12,43,342,9));
If the array has keys, the keys will be the corresponding x-axis values.
$data = array("1" => 100, "2" => 12, "3" => 43, "4" => 342, "5" => 9);
I need to dynamically build the $data array, starting with a key value of "1", and assign values from a variable separated by commas. The amount of values can change. For example:
$values="100,12,43,342,9,22,33";
I could explode the data into an array
$splits = explode(",",$values);
Now I have the number of values. So how do I code a loop to assign these values to incremental keys so that the $data array is essentially:
$data = array("1" => 100, "2" => 12, "3" => 43, "4" => 342, "5" => 9, "6" => 22, "7"=> 33);
Upvotes: 1
Views: 189
Reputation: 1553
This should start the array as one indexed.
<?php
$values = "100,12,43,342,9,22,33";
$splits = explode(",", $values);
$data = array_combine(range(1, count($splits)), array_values($splits));
$data = array_map('intval', $data); // converts values to int
var_dump($data);
Upvotes: 2
Reputation: 726
something like this ?
<?php
$values="100,12,43,342,9,22,33";
$splits = explode(",",$values);
$data = array();
for ($x = 0; $x < count($splits); $x++) {
$data[$x+1] = intval($splits[$x],10);
}
var_dump($data);
Upvotes: 3