我尝试使用 json_encode 将 PHP 数组存储为 javascript 数组,但是当我尝试显示 javascript 数组或引用它的索引时,它显示为空或未定义。
我基本上想要做的是采用四个不同的 PHP 数组($lids、$dates、$prices、$scaledPrices)并将它们组合成一个数组,以便这个新数组的每个元素都包含原始四个数组中每个数组的相应索引(即 new_array = [[5001, 2020-01-01, $100.00, $110.00], [5002, 2020-01-021, $103.45, $103.23], ...]
我能够成功地使用 MultipleIterator 功能正确组合四个 PHP 数组,因为它正确显示,但我似乎无法将其存储在 javascript 数组中。有什么建议么?
// initialize php arrays to populate and use for chart
$dates = array_column($priceData, 'date');
$scaledPrices = array_column($priceData, 'scaledP');
// arrays used for chart must be reversed and json_encoded
$chart_dates = json_encode(array_reverse($dates));
$chart_scaledPrices = json_encode(array_reverse($scaledPrices));
// initialize $lids and $prices arrays to use for download
$lids = array_column($priceData, 'lid');
$prices = array_column($priceData, 'price');
// combine $lids, $dates, $prices, and $scaledPrices into one array
$csv_lids = new ArrayIterator($lids);
$csv_dates = new ArrayIterator($dates);
$csv_prices = new ArrayIterator($prices);
$csv_scaledPrices = new ArrayIterator($scaledPrices);
$csv_data = new MultipleIterator(MultipleIterator::MIT_KEYS_NUMERIC);
$csv_data->attachIterator($csv_lids);
$csv_data->attachIterator($csv_dates);
$csv_data->attachIterator($csv_prices);
$csv_data->attachIterator($csv_scaledPrices);
// this correctly loops through and displays the new array
foreach ($csv_data as $item) {
echo "<pre>";
print_r($item);
echo "</pre>";
}
?>
<!-- store php csv array as javascript array variable -->
<script>
// var js_csv_data = new Array();
var js_csv_data = <?php echo json_encode($csv_data); ?>
// this shows as an emtpy object . . . even without JSON.stringify
console.log(JSON.stringify(js_csv_data));
// this shows as undefined . . . even without JSON.stringify
console.log(JSON.stringify(js_csv_data[0]));
</script>