PHP - Append elements to array

2019-03-03 20:52发布

I have an array that is used to render a graph using PHPGraphLib. I can make this work fine, but only with hard coded values.

I get "POSSIBLE syntax error" warning from Netbeans.

What is the correct way of appending elements to this type of array?

//Create new graph object and add graph data
$graph = new PHPGraphLib(650,400);
$data = array           ("00:00" => -9,
                        "00:15" => -8,
                        "00:30" => -3.5,
                        "00:45" => 5, 
                        "01:00" => 11,
                        "01:15" => 12.5,
                        "01:30" => 10.5,
                        "01:45" => 11,
                        "02:00" => 2,
                        "02:15" => -2,
                        "02:30" => 2,
                        "02:45" => -2,
                        "03:00" => 14);

array_push($data, "03:15" => 16);  //This is the part I cannot get to work

//Plot data
$graph->addData($data);

3条回答
孤傲高冷的网名
2楼-- · 2019-03-03 21:17

The syntax to add a new element to an associative array is:

$data["03:15"] = 16;

array_push is used with values, not associative elements. It's normally used only with arrays that have numeric indexes, not associative arrays, as it generates the key by adding 1 to the highest numeric index in the array.

查看更多
干净又极端
3楼-- · 2019-03-03 21:26

Replace your array_push(...) with this:

$data['03:15'] = 16;

With array_push() you can only add values to arrays. Not keys as you want.

查看更多
迷人小祖宗
4楼-- · 2019-03-03 21:34

Just append it using shorthand syntax:

$data["03:15"] = 16;
查看更多
登录 后发表回答