如何使用json数组格式化json

时间:2014-03-06 07:03:07

标签: php json

我希望json中的输出像这样

response:{url="www.google.com/raj.png", size=12.344KB},{url="www.google.com/raj2.png", size=12.344KB},{url="www.google.com/raj4.png", size=12.344KB}

但目前我正在

"url=> www.google.com/img1.png size => 12.344 KB,url=> www.google.com/img2.png size => 12.344 KB"

3 个答案:

答案 0 :(得分:2)

//Using some loop here
{
  $response[] = array('url' => 'url_value','size' => 'file_size');
}

//without loop hardcoded values:

$response = array ( array('url' => "www.google.com/raj.png",'size' => "12.344KB"),
array('url' => "www.google.com/img2.png",'size' => "10.344KB") );

return json_encode($response);

答案 1 :(得分:0)

$out= Array(
 Array('url'=>'www.goog', 'size'=>'12KB'),
 Array('url'=>'moogle', 'size'=>'13KB')
);
echo Json_encode($out);

答案 2 :(得分:0)

不确定如何格式化数组,但是如果你这样定义它应该可以做到这一点:

$response_array = array(
  'response' => array(
    array(
      'url'  => 'www.google.com/raj.png',
      'size' => '12.344KB',
    ),
    array(
      'url'  => 'www.google.com/raj.png',
      'size' => '12.344KB',
    ),
    array(
      'url'  => 'www.google.com/raj.png',
      'size' => '12.344KB',
    ),
  ),
);

$respose_json = json_encode($response_array);
echo($response_json);

要循环显示某些结果,请尝试以下操作:

$response_array = array('response' => array());
foreach($result_set as $result_item) {
  $response_item = array();
  $response_item['url'] = $result_item['url'];
  $response_item['size'] = $result_item['size'];
  $response_array['response'][] = $response_item;
}

$respose_json = json_encode($response_array);
echo($response_json);

上面的$result_set是你从数据库,服务器等中提取的数据。