我正在努力克服我的一个PHP脚本中的错误。 这是一个我无法解释的奇怪行为。请帮我。首先:
$php -v
PHP 7.0.7 (cli) (built: May 25 2016 18:40:26) ( NTS )
在我的脚本中,我运行了一个MySQL查询,该查询正在成功。其次我这样做:
while ($z = mysqli_fetch_array($req)) {
if (!isset($datenGraph[$z[0]])) {
$datenGraph[$z[0]] = [];
} //just fill the array with zeros before and after the result
while (count($datenGraph[$z[0]]) < ($z[2] - 1)) {
array_push($datenGraph[$z[0]], 0);
}
array_push($datenGraph[$z[0]], (int)$z[3]);
}
foreach ($datenGraph as $key => &$value) {
while (count($value) < 12) {
array_push($value, 0);
}
}
但是上面的代码不是问题。在那里我创建了一个如下所示的数组(数组键 - >值,它包含数组):
array (size=4)
'Numerber1' =>
array (size=12)
0 => int 0 1 => int 0 2 => int 0 3 => int 0
4 => int 2 5 => int 16 6 => int 0 7 => int 0
8 => int 0 9 => int 0 10 => int 0 11 => int 0
'Number2' =>
array (size=12)
0 => int 0 1 => int 0 2 => int 0 3 => int 0
4 => int 2 5 => int 7 6 => int 0 7 => int 0
8 => int 0 9 => int 0 10 => int 0 11 => int 0
'Number3' =>
array (size=12)
0 => int 0 1 => int 0 2 => int 0 3 => int 0
4 => int 0 5 => int 8 6 => int 0 7 => int 0
8 => int 0 9 => int 0 10 => int 0 11 => int 0
'Number4' =>
array (size=12)
0 => int 0 1 => int 0 2 => int 0 3 => int 0
4 => int 0 5 => int 7 6 => int 0 7 => int 0
8 => int 0 9 => int 0 10 => int 0 11 => int 0
请注意,所有元组都不同(正确的数据)。 现在是棘手的部分。在评估此数组时,最后一个元组的内容会更改为前一个元组!无论数组中有多少元组。
以下是它的样子:
foreach ($datenGraph as $key => $value) {
print_r($value);
}
打印相同的最后2个元组:
Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 2 [5] => 16 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 )
Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 2 [5] => 7 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 )
Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 8 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 )
Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 8 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 )
下一个打印出与上面相同的错误。:
$valueSet2 = array_values($datenGraph);
foreach ($valueSet2 as $key => $value) {
print_r($value);
}
但会打印出正确的内容。
$valueSet2 = array_values($datenGraph);
function console_log( $data )
{
echo '<script>';
echo 'console.log(' . json_encode( $data ) . ')';
echo '</script>';
}
console_log($valueSet2);
给予:[[0,0,0,0,2,16,0,0,0,0,0,0],[0,0,0,0,2,7,0,0,0,0,0,0],[0,0,0,0,0,8,0,0,0,0,0,0],[0,0,0,0,0,7,0,0,0,0,0,0]
从这里得到正确的结果(双json_encode)(获取字符串):
$valueSet2 = json_encode(array_values($datenGraph));
console_log($valueSet2);
更令人困惑的是。请注意前两个示例中的json_encode
打印正确的内容。现在我正在尝试这样做(下面几行):
<?php
$x=0;
foreach ($datenGraph as $key => $value) {
echo 'label: ' . '\'' . $key . '\'' . ' , ' . PHP_EOL;
echo 'backgroundColor: [' . 'randomColor() . ']' . ', ' . PHP_EOL;
echo 'data: ' . json_encode($valueSet2[$x]) . PHP_EOL;
if ($x < $keySetSize - 1){
echo '}, {' . PHP_EOL;
}
$x=$x+1;
}
?>
在最后一次迭代中,我再次得到错误的元组,而不像之前使用json_encode
的2个例子给出了期望的结果。我做错了什么?请帮忙。谢谢!