开发者

json encoding using php

i am new to JSON and i have e datas returning form db eg

example
   example1
   example2
sample
   sample1
   sample 2

like this i need to convert it to json like this {'title':'Heavy Metal', 'results': [ ['/metal/1', 'Disturbed - The Game', 'icons/metal.png'], ['/metal/2', 'Marilyn Manson - The Beautiful People', 'icons/metal.png'], ['/metal/3', 'Soil - 2 Skins', 'icons/metal.png'], ['/metal/4', 'Alestorm - Wenches & Mead', 'icons/metal.png'] ]}, {'title':'Pop', 'results':[ ['/pop/1', 'Michael Jackson - Bad', 'icons/pop.png'], ['/p开发者_C百科op/2', 'Britney Spears - If U Seek Amy', 'icons/pop.png'], ['/pop/3', 'Take That - Relight My Fire', 'icons/pop.png'], ['/pop/4', 'Rick Astley - Never Gonna Give You Up', 'icons/pop.png'] ]}, if i use json_encode simply i am getting "example","example1" etc how can i attain this format.


If you can get the data you need to format in an array in PHP, using json_encode will work great for you.

For example:

array(
    "Key1" => "Value1",
    "Key2" => "Value2",
    "Key3" => "Value3
);

converted using json_encode would give you:

{ "Key1": "Value1", "Key2": "Value2", "Key3": "Value3" }


    $rs=mysql_query($sql);
    $data = array();

    while ($row=@mysql_fetch_object($rs)){
                $data [] = $row;
   }            
   $connections=json_encode($data);
  echo $msg= "{'success': true,'message':'online users','online_users':'$connections'}";

Declare an array , paas all result of query in the array and use json_encode. Good Luck .


You can use this little PHP library. It sends the headers and give you an object to use it easily.

It looks like :

<?php
// Include the json class
include('includes/json.php');

// Then create the PHP-Json Object to suits your needs

// Set a variable ; var name = {}
$Json = new json('var', 'name'); 
// Fire a callback ; callback({});
$Json = new json('callback', 'name'); 
// Just send a raw JSON ; {}
$Json = new json();

// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';

// Add some content
$Json->addContent(new propertyJson('width', '565px'));
$Json->addContent(new textJson('You are logged IN'));
$Json->addContent(new objectJson('An_Object', $object));
$Json->addContent(new arrayJson("An_Array",$arraytest));
$Json->addContent(new jsonJson("A_Json",$jsonOnly));

// Finally, send the JSON.

json_send($Json)
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜