我有一个URL可以给我这个结果:
{"status":"ok","result":[{"account":"11754-101","name":"test","channels":"15","billing":"1","billingstep":"60","increment":"0","credit":"1.0089"},{"account":"11754-102","name":"mult","channels":"15","billing":"1","billingstep":"60","increment":"0","credit":"2.7835"}]}
我正在尝试仅查看一个帐户的“信用”值。
Account: 11754-102
Credit: XXX
我执行的代码是这样,但似乎已损坏:
<?php
$json = '{"status":"ok","result":[{"account":"11754-101","name":"test","channels":"15","billing":"1","billingstep":"60","increment":"0","credit":"1.0089"},{"account":"11754-102","name":"mult","channels":"15","billing":"1","billingstep":"60","increment":"0","credit":"2.7835"}]}';
$apiResult = json_decode($json, true);
($apiResult['status'] !== 'ok') &&
trigger_error('Unexpected API Result');
empty(($account = array_filter($apiResult['result'], function($item) {
return $item['account'] === '11754-102';
}))) && trigger_error('Account not found.');
echo $account[0]['credit'];
?>
你能帮我吗?
答案 0 :(得分:2)
当简单的^\w*?\d[a-zA-Z]*?[\s]?.*$
可以使用快捷方式时,并不太喜欢使用快捷方式,但是主要的问题是,当您结束学习时,就会使用
if()
如果您查看echo $account[0]['credit'];
的输出,在这种情况下,您将得到...
array_filter()
因此,尽管它只有一个元素,但它是元素1而不是0。
我已经重写了代码以将其纳入accounf(并添加了一些Array
(
[1] => Array
(
[account] => 11754-102
[name] => mult
[channels] => 15
[billing] => 1
[billingstep] => 60
[increment] => 0
[credit] => 2.7835
)
)
)...
if
答案 1 :(得分:0)
由于我不知道您是否收到错误消息,因此如果要显示错误,可以使用本文来做:How do I get PHP errors to display?
问题是$account[0]
不存在,$account["result"][0]
存在。因此代码将为echo $account['result'][0]['credit'];
答案 2 :(得分:0)
这是您的更正代码。您可以使用array_pop实现相同的目的。您的帐户的抵销金额为1,但您的提取金额为0。
<?php
$json = '{"status":"ok","result":[{"account":"11754-101","name":"test","channels":"15","billing":"1","billingstep":"60","increment":"0","credit":"1.0089"},{"account":"11754-102","name":"mult","channels":"15","billing":"1","billingstep":"60","increment":"0","credit":"2.7835"}]}';
$apiResult = json_decode($json, true);
($apiResult['status'] !== 'ok') &&
trigger_error('Unexpected API Result');
empty(($account = array_filter($apiResult['result'], function($item) {
return $item['account'] === '11754-102';
}))) && trigger_error('Account not found.');
echo array_pop( $account )['credit'];
?>