Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
134
rated 0 times [  140] [ 6]  / answers: 1 / hits: 52362  / 13 Years ago, tue, november 29, 2011, 12:00:00

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


More From » php

 Answers
6

As the comment says you should consider using (php function)json_encode instead, which will turn...



php:

$a = array(
array(gender=> male, name=> Bob),
array(gender=> female, name=> Annie)
);

Into json:
[
{gender:male, name:Bob},
{gender:female, name:Annie}
]


Echoing json_encode($a) would output it just like that.


[#88854] Sunday, November 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hasanb

Total Points: 321
Total Questions: 102
Total Answers: 96

Location: Burkina Faso
Member since Fri, Sep 4, 2020
4 Years ago
;