在PHP中将单个Json对象转换为Json数组

时间:2018-02-12 20:35:20

标签: php arrays json

我正在调用coincap.io单个JSON对象

{"altCap":282255454377.94916,"bitnodesCount":11508,"btcCap":149160858393,"btcPrice":8830.18849156212,"dom":63.86,"totalCap":431416312770.94904,"volumeAlt":709387849.4057536,"volumeBtc":1253729369.908587,"volumeTotal":1963117219.314342}

我想成为像

这样的数组
[{"altCap":282255454377.94916,"bitnodesCount":11508,"btcCap":149160858393,"btcPrice":8830.18849156212,"dom":63.86,"totalCap":431416312770.94904,"volumeAlt":709387849.4057536,"volumeBtc":1253729369.908587,"volumeTotal":1963117219.314342}]

这是我的主要php类

Class Second {
 private function request($url)
     {


         $curl = curl_init();

         curl_setopt_array($curl, array(
             CURLOPT_RETURNTRANSFER => 1,
             CURLOPT_URL => $url,
             CURLOPT_USERAGENT => 'Agent'
         ));

         return curl_exec($curl);

         curl_close($curl);

     }

     public function jsonCache($ctime)
     {
         global $request_type, $purge_cache, $limit_reached, $request_limit;

         $cache_file = dirname(__FILE__) . '/data/global.json';
         $expires    = time() - $ctime;

         if (!file_exists($cache_file))
             die("Cache file is missing: $cache_file");

         if (filectime($cache_file) < $expires || file_get_contents($cache_file) == '' || $purge_cache && intval($_SESSION['views']) <= $request_limit) {

             $query = 'https://coincap.io/global';

             $api_results  = $this->request($query);

             $json_results = $api_results;

             if ($api_results && $json_results)
                 file_put_contents($cache_file, $json_results);


         } else {

             $json_results = file_get_contents($cache_file);
             $request_type = 'JSON';
         }

         return $json_results;
     }

}

?>

任何想法如何把它放在方括号? 已经为数组使用相同的PHP类并且工作正常 但是我希望这个单个对象有用JSON文件写的方括号

1 个答案:

答案 0 :(得分:0)

在return语句中,只需连接括号

return '['.$json_result.']';