1

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);
1
  • have you looked at for each loop in the php docs and make a new array as you loop through Commented Apr 23, 2016 at 22:25

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

That's why I did but it wasn't working. So I added the var_dump and realized the data was being assigned as a string, not an integer (that PHPGraphlib required). So I made one change to your code and it now works. Thank you! Changed $data[$x+1] = (int)$splits[$x];
Good as gold, realized that might be the case so check edit you can also use floatval, snap! nice
2

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);

2 Comments

No problem, could you mark one of the answers as the solution please?
I liked your answer because it used standard php function, however as each function must in someway loop I tested your code vs mine and performance is far slower using your method

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.