dongquxiao8545 2018-08-16 14:05
浏览 186
已采纳

如何在PHP中解析具有变量和显示最大值的JSON数组中的列? [重复]

This question already has an answer here:

I have a JSON array, I get it from the REST API using curl and I want to get all the numbers from the "c" column and then find the maximum.

function part of my code

curl_setopt($ch, CURLOPT_URL, "https://api-domain.com/v3/instruments/" . $ticker . "/candles?&price=A&from=" . $first . "&to=" . $second . "&granularity=D");
// get stringified data/output. See CURLOPT_RETURNTRANSFER
$data = curl_exec($ch);
// get info about the request
$info = curl_getinfo($ch);
// close curl resource to free up system resources
curl_close($ch);
$json_string = $data;
$jsondata = ($json_string);
$obj = json_decode($jsondata,true);
print_r($jsondata); //below get the answer

//(print_r output)

{
"instrument":"EUR_USD",
"granularity":"D",
"candles":[
{
"complete":true,
"volume":32813,
"time":"2017-01-02T22:00:00.000000000Z",
"ask":{
"o":"1.04711",
"h":"1.04908",
"l":"1.03413",
"c":"1.04061"
}
},
{
"complete":true,
"volume":34501,
"time":"2017-01-03T22:00:00.000000000Z",
"ask":{
"o":"1.04076",
"h":"1.05009",
"l":"1.03907",
"c":"1.04908"
}
},
{
"complete":true,
"volume":52627,
"time":"2017-01-04T22:00:00.000000000Z",
"ask":{
"o":"1.04911",
"h":"1.06161",
"l":"1.04816",
"c":"1.06083"
}}]}
</div>
  • 写回答

2条回答 默认 最新

  • doujiao3998 2018-08-16 15:09
    关注

    You need to do following to get desired output.

    1. Decode json
    2. Map array
    3. Sort

    Snippet

    $data = '{
    "instrument":"EUR_USD",
    "granularity":"D",
    "candles":[
    {
    "complete":true,
    "volume":32813,
    "time":"2017-01-02T22:00:00.000000000Z",
    "ask":{
    "o":"1.04711",
    "h":"1.04908",
    "l":"1.03413",
    "c":"1.04061"
    }
    },
    {
    "complete":true,
    "volume":34501,
    "time":"2017-01-03T22:00:00.000000000Z",
    "ask":{
    "o":"1.04076",
    "h":"1.05009",
    "l":"1.03907",
    "c":"1.04908"
    }
    },
    {
    "complete":true,
    "volume":52627,
    "time":"2017-01-04T22:00:00.000000000Z",
    "ask":{
    "o":"1.04911",
    "h":"1.06161",
    "l":"1.04816",
    "c":"1.06083"
    }}]}';
    
    $arr = json_decode($data,true);
    
    $c = array_map( function ($in){
    return  $in['ask']['c'];
    }, $arr['candles']);
    
    sort($c);
    
    echo 'Min is: '.current($c)."
    ";
    echo 'Max is: '.end($c);
    

    Output

    Min is: 1.04061
    Max is: 1.06083
    

    Live demo

    Docs

    1. array_map
    2. sort
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!