我正在尝试使用 foreach 检索 json 中所有市场对的列表。我希望结果是这样的
["BTC","LTC","ETH","NEO","BNB","QTUM","EOS","SNT","BNT","GAS","BCC","USDT","HSR","OAX","DNT","MCO","ICN","ZRX","OMG","WTC","YOYO","LRC","TRX"]
但是,如果我使用 json_response 函数,我只会得到 BTC 或第一个值,如果我使用 echo 或 print,我会得到一个像 BTCLTCETH 这样的字符串,这意味着它获取值,但它们只是一个大字符串。这是我的foreach。任何帮助表示赞赏。
代码
$api = new Binance\API($key,$secret);
$exchangeInfo = $api->exchangeInfo();
foreach($exchangeInfo['symbols'] as $info) {
json_response($info['symbol']);
}
json_response 函数
function json_response($data=null, $httpStatus=200)
{
header_remove();
header("Content-Type: application/json");
http_response_code($httpStatus);
echo json_encode($data);
exit();
}
exchangeInfo 函数响应看起来像这样一对
{
"timezone": "UTC",
"serverTime": 1565246363776,
"rateLimits": [
{
}
],
"exchangeFilters": [
],
"symbols": [
{
"symbol": "ETHBTC",
"status": "TRADING",
"baseAsset": "ETH",
"baseAssetPrecision": 8,
"quoteAsset": "BTC",
"quotePrecision": 8, // will be removed in future api versions (v4+)
"quoteAssetPrecision": 8,
"baseCommissionPrecision": 8,
"quoteCommissionPrecision": 8,
"orderTypes": [
"LIMIT",
"LIMIT_MAKER",
"MARKET",
"STOP_LOSS",
"STOP_LOSS_LIMIT",
"TAKE_PROFIT",
"TAKE_PROFIT_LIMIT"
],
"icebergAllowed": true,
"ocoAllowed": true,
"quoteOrderQtyMarketAllowed": true,
"isSpotTradingAllowed": true,
"isMarginTradingAllowed": true,
"filters": [
//These are defined in the Filters section.
//All filters are optional
],
"permissions": [
"SPOT",
"MARGIN"
]
}
]
}
我需要从中提取所有“符号”值
答案 0 :(得分:2)
不要在循环中回显 JSON 字符串 X 时间。在循环中构建一个数组并从构建的数组中回显 JSON 字符串 ONCE。
看起来您也是从数据结构中的错误位置获取数据!
"symbol": "ETHBTC"
不是您想要的。可能你需要
"baseAsset": "ETH"
和/或
"quoteAsset": "BTC"
$results = [];
foreach($exchangeInfo['symbols'] as $info) {
$results[] = $info['quoteAsset']; // or maybe baseAsset or maybe both
}
json_response($results);
<块引用>
此外,您可能还想从 exit()
函数中删除 json_response()
。在函数中具有危险的副作用。如果您需要在调用后退出,请将 exit
放在调用 json_response()
之后,但不要认为这将始终是您在终止脚本之前要做的最后一件事。