I've tried using json_encode to store a PHP array as a javascript array, but when I try to display the javascript array or reference an index of it, it shows as empty or undefined.
What I basically want to do is take four different PHP arrays ($lids, $dates, $prices, $scaledPrices) and combine them into one array so that each element of this new array contains the corresponding index from each of the original four arrays (i.e. new_array = [[5001, 2020-01-01, $100.00, $110.00], [5002, 2020-01-021, $103.45, $103.23], . . . ]
I'm able to successfully use the MultipleIterator feature to correctly combine the four PHP arrays as this display correctly, but I can't seem to then store this in a javascript array. Any suggestions?
how to assign php array values to javascript array
// 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>
console.log(js_csv_data)
? can you post the output?