This question already has an answer here:
I have a javascript question. What the best way of writing the following Javascript code dynamically. Keep in mind that I have to write the code using php echo tags. So the browser can translate it a JavaScript. Thanks
var one = {
info: { name: "John" }
};
var two = {
info: { name: "Henry" }
};
var simple_config = [ one,two ];
//SOLUTION
<script>
var page = <?php echo json_encode($tree_data->result_array()); ?>
<?php
var $page_data = echo json_encode($tree_data->result_array()); // assoc array from database
foreach ($page as $row){
echo 'var $row['student_number'] = {
text: { name: "Name" }
};';
echo " var class = [];";
echo "class.push($row['student']);";
}?>
</script>
<script>
new ClassRegistry(simple_chart_config); //pre-defined custom function
</script>
</div>
json_encode
would do the trick. However if you still want to do it your way, you can use code below as starting point.
Something like that would do it.
$myArr = ['name' => 'Test'];
print "var one = {"; //Variable declaration
foreach ($myArr as $k => $v) {
print $k . ': "' . $v . '",'; //All the keys and values
}
print "};" //Close brackets
This would print:
var one = {name: "Test",};