1

我目前正在处理 phplot,我想在其中添加多条线的折线图。

所以这就是问题所在,假设我有一个数据数组:

$graph->SetDataType('data-data');
$data = array(
     array("",0,37.0023239,34.4618,31.92128),
     array("",1,39.6116079,37.2759,34.94019),
     array("",2,41.4738623,39.1285,36.78314)
);

现在我有了另一个数组,我们称它为 a,其中的键实际上是我想将其放入数据数组中的位置:

$a = array (
    "0"=>'38';
    "2"=>'40';
)

我希望数据将它们插入到相应的 x 值中。所以最后,我想要类似的东西:

$data = array(
     array("",0,37.0023239,34.4618,31.92128,38),
     array("",1,39.6116079,37.2759,34.94019,''),
     array("",2,41.4738623,39.1285,36.78314,40)
);

是否有可能做到这一点?任何建议将不胜感激。

4

2 回答 2

2

应该相当简单:

foreach($data as $key => &$val) {
    if(isset($a[$key])) {
        $val[] = $a[$key];
    } else {
        $val[] = '';
    }
}
于 2015-01-20T16:10:25.683 回答
2

与上一个答案几乎相同,但将查找由内而外:迭代数据数组并检查每个键值对是否$a包含相应的元素;是:附加它,否:附加一个空字符串。

<?php
$data = array(
     array("",0,37.0023239,34.4618,31.92128),
     array("",1,39.6116079,37.2759,34.94019),
     array("",2,41.4738623,39.1285,36.78314)
);

$a = array (
    "0"=>'38',
    "2"=>'40',
);

foreach($data as $k=>&$v) {
    $v[] = isset($a[$k]) ?  $a[$k] : '';
}

var_export($data);

印刷

array (
  0 => 
  array (
    0 => '',
    1 => 0,
    2 => 37.0023239,
    3 => 34.461799999999997,
    4 => 31.921279999999999,
    5 => '38',
  ),
  1 => 
  array (
    0 => '',
    1 => 1,
    2 => 39.611607900000003,
    3 => 37.2759,
    4 => 34.940190000000001,
    5 => '',
  ),
  2 => 
  array (
    0 => '',
    1 => 2,
    2 => 41.4738623,
    3 => 39.128500000000003,
    4 => 36.783140000000003,
    5 => '40',
  ),
)
于 2015-01-20T16:14:49.330 回答