user1619228
user1619228

Reputation: 63

Group JSON using PHP

This is my code

<?php
$something = array(); 
while ($row = mysql_fetch_assoc($result)) { 
    $something[] = $row;
} 
mysql_close($con);
?>

<script type="text/javascript"> 
    some= <?php echo json_encode($something); ?>; 
</script>

The above code will generate:

[{"id":"1","title":"Ray","author":"Ray","thumb":"some source","views":"10000"}]

But I want to generate a json string like this:

[{"id":"1","title":"Ray","author":"Ray","image":{"cls":"image","thumb":"some source","views":"10000"}}]

Any help ?

Upvotes: 0

Views: 695

Answers (1)

naivists
naivists

Reputation: 33501

json_encode encodes whatever object structure you have. If you want certain properties to be as sub-object, you have to create such object in memory..

For instance, if you had

$a = array("id"=>1, 
           "title"=>"Ray", 
           "image" => 
               array(
                 "thumb"=>"some source",
                 "cls"=>"image"
                )
           );

it would encode in json in a similar way you are mentioning.

This means that you have to loop through mysql results and create the new structure before. Then call json_encode on it.

Upvotes: 3

Related Questions