如何在PHP中解析具有变量的JSON数组中的列并显示最大值?

时间:2018-08-16 14:05:09

标签: php arrays json

我有一个JSON数组,我使用curl从REST API中获取它,我想从“ c” 列中获取所有数字,然后找到最高

我代码的功能部分

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输出

{
"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"
}}]}

2 个答案:

答案 0 :(得分:0)

您可以使用array_map()anynomous function构建收盘价数组,然后使用max()获得最高价:

// This will return an array of the close prices
$close_prices = array_map(function ($candle) {
    return $candle['ask']['c'];
},
$jsondata['candles']); // <-- Of course send the candlesticks array

// Now get the highest value in the close prices array
$highest = max($close_prices);


echo 'Maximum EUR/USD value: 1 EUR = ' . $highest . ' USD';
// Maximum EUR/USD value: 1 EUR = 1.06083 USD

相同的代码,较短:

$highest = max(array_map(function($c) { return $c['ask']['c']; }, $jsondata['candles']));

答案 1 :(得分:0)

您需要执行以下操作以获得所需的输出。

  1. 解码json
  2. 地图数组
  3. 排序

摘要

$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)."\n";
echo 'Max is: '.end($c);

输出

Min is: 1.04061
Max is: 1.06083

实时demo

文档

  1. array_map
  2. sort