我正在尝试从嵌套数组中提取数据,但我无法提出可行的解决方案。 JSON数组是:
{
"Body": {
"stkCallback": {
"MerchantRequestID": "26452-605723-2",
"CheckoutRequestID": "ws_CO_23042018105859659",
"ResultCode": 0,
"ResultDesc": "The service request is processed successfully.",
"CallbackMetadata": {
"Item": [
{
"Name": "Amount",
"Value": 1
},
{
"Name": "MpesaReceiptNumber",
"Value": "MDN6ZJE4XG"
},
{
"Name": "Balance"
},
{
"Name": "TransactionDate",
"Value": 20180423105912
},
{
"Name": "PhoneNumber",
"Value": 254722200121
}
]
}
}
}
}
这是我提取的PHP代码,Amount,MpesaReceiptNumber,PhoneNumber,TransactionDate: 我可以使用下面的代码阅读第一部分而不是第二部分:
$arrContextOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, ), );
$data = @file_get_contents( $url, false, stream_context_create( $arrContextOptions ) );
if ( $data != '' ) {
$arr = json_decode($data, true);
echo $string = $arr['Body']['stkCallback']['MerchantRequestID']; // Working
echo $string = $arr['Body']['stkCallback']['MerchantRequestID']['Item'][0]; //Not Working
}
答案 0 :(得分:0)
将您的JSON与JsonLint
一起使用我们看到您尝试通过调用ID MerchantRequestID
您已尝试在数组键中设置错误的路径
print_r($arr['Body']['stkCallback']['CallbackMetadata']['Item'][0]);
而不是
echo $string = $arr['Body']['stkCallback']['MerchantRequestID']['Item'][0];
我使用print_r
方法,因为您无法echo
数组
答案 1 :(得分:0)
它应该是:
echo $string = $arr['Body']['stkCallback']['CallbackMetadata']['Item'][0];
答案 2 :(得分:0)
["item"][0]
是一个数组,无法回显
您需要回复["name"]
中的[0]
。
echo $arr['Body']['stkCallback']['MerchantRequestID'] . "\n"; // Working
Foreach($arr['Body']['stkCallback']['CallbackMetadata']['Item'] as $subarr){
Foreach($subarr as $item){
Echo $item ."\n";
}
}