I’m quite new to working with JSON.
My current script outputs the following JSON:-
{"comments":[[17.9775280899,"2011-09-28 14:38:41","admin","1","2","http:\/\/www.example.com\/members\/admin\/","http:\/\/www.example.com\/wp-content\/uploads\/avatars\/1\/8bb11e958a26913e2c13393014e854d5-bpthumb.jpg","admin"],
[0.749063670412,"2011-09-28 14:43:11","admin","1","3","http:\/\/www.example.com\/members\/admin\/","http:\/\/www.example.com\/wp-content\/uploads\/avatars\/1\/8bb11e958a26913e2c13393014e854d5-bpthumb.jpg","admin"],
[36.329588015,"2011-10-06 14:15:12","admin","1","10","http:\/\/www.example.com\/members\/admin\/","http:\/\/www.example.com\/wp-content\/uploads\/avatars\/1\/8bb11e958a26913e2c13393014e854d5-bpthumb.jpg","admin"]]}
However I would like to add a name/tag to each individual piece of data e.g. ‘leftPercent’, ‘timestamp’, ‘username’ etc.
This is the relevant part of my script:
First I get the data from the database…
$sQuery = "
select cp_comments.*,users.user_login, users.user_url, users.display_name, users.ID as avatar
from ".$wpdb->prefix."cp_comments cp_comments
left join ".$wpdb->prefix."users users on users.ID=cp_comments.uid
where songid='$id'
order by cp_comments.id asc
";
$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
Then I do some custom formatting on the data. (There will be other items added later, for now it is just comments.
$output = array(
"comments" => array()
);
while ( $aRow = mysql_fetch_array( $rResult ) )
{
$row = array();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $aColumns[$i] == "playtime" )
{
/* Special output formatting for 'playtime' column */
$row[] = ($aRow[ $aColumns[$i] ]) / $duration * 100;
}
else if ( $aColumns[$i] == "avatar" )
{
/* Special output to render Avatar by user id */
$row[] = commentplayer_get_user_avatar($aRow[ $aColumns[$i] ]);
}
else if ( $aColumns[$i] != ' ' )
{
/* General output */
$row[] = $aRow[ $aColumns[$i] ];
}
}
$output['comments'][] = $row;
}
And finally I encode the JSON:
echo json_encode($output);
What part am I missing? I’m sure this is very simple. Thanks all.
If the
$aColumns[$i]corresponds to the name column from a database query, then try thisI changed
$row[]to$row[$aColumns[$i]]