I’m trying to create an object in javascript with PHP. This is my script:
<script>
$(document).ready(function(){
var genres = [
<?php
$last = count($userGenres) - 1;
$i = 0;
foreach($userGenres as $a){
$i++;
echo '{"value":"'.$a['genre'].'", "name":"'.$a['name'].'"}';
if($i < $last){
echo ',';
}
}
?>
];
});
</script>
When I check the generated source, it creates a valid object, but the whole script in that tag doesn’t work now. How would fix this, without JSON?
Thanks
As the comment says you should consider using (php function)json_encode instead, which will turn…
Echoing json_encode($a) would output it just like that.