如何迭代嵌套在数组中的数组
How to iterate arrays nested in arrays
下面有 json 数组,我正在尝试访问 ProductResults 位。
我希望输出是这样的:
Term: 47, Type:HP, Payment: 229.4
Term: 47, Type:PCP, Payment: 172.23
Term: 60, Type:PCP, Payment: 186.82
但我什至难以访问数组的其他部分。
PHP:
$json = json_decode($resp, true);
foreach ($json['VehicleResults'] as $item)
{
$data = $item['FinanceProductResults'];
$v0 = $data['Term'];
echo $v0;
}
JSON:
{
"VehicleResults": [{
"Id": "0",
"FinanceProductResults": [{
"Term": 47,
"AnnualMileage": 6000,
"Deposits": 1000,
"ProductResults": [{
"Key": "HP",
"Payment": 229.4
}, {
"Key": "PCP",
"Payment": 172.23
}]
}, {
"Term": 60,
"AnnualMileage": 6000,
"Deposits": 1000,
"ProductResults": [{
"Key": "HP",
"Payment": 186.82
}]
}]
}]
}
FinanceProductResults
也是一个数组,所以它也需要作为一个数组来访问。就像您访问了 VehicleResults
一样,ProductResults
也是如此。所以你的代码应该看起来像这样。
$json = json_decode($resp, true);
foreach ($json['VehicleResults'] as $item)
{
$dataItems = $item['FinanceProductResults'];
foreach ($dataItems as $data) {
$v0 = $data['Term'];
foreach ($data['ProductResults'] as $productResult) {
$type = $productResult['Key'];
$payment = $productResult['Payment'];
echo "Term: $v0, Type: $type, Payment: $payment";
}
}
}
下面有 json 数组,我正在尝试访问 ProductResults 位。
我希望输出是这样的:
Term: 47, Type:HP, Payment: 229.4
Term: 47, Type:PCP, Payment: 172.23
Term: 60, Type:PCP, Payment: 186.82
但我什至难以访问数组的其他部分。
PHP:
$json = json_decode($resp, true);
foreach ($json['VehicleResults'] as $item)
{
$data = $item['FinanceProductResults'];
$v0 = $data['Term'];
echo $v0;
}
JSON:
{
"VehicleResults": [{
"Id": "0",
"FinanceProductResults": [{
"Term": 47,
"AnnualMileage": 6000,
"Deposits": 1000,
"ProductResults": [{
"Key": "HP",
"Payment": 229.4
}, {
"Key": "PCP",
"Payment": 172.23
}]
}, {
"Term": 60,
"AnnualMileage": 6000,
"Deposits": 1000,
"ProductResults": [{
"Key": "HP",
"Payment": 186.82
}]
}]
}]
}
FinanceProductResults
也是一个数组,所以它也需要作为一个数组来访问。就像您访问了 VehicleResults
一样,ProductResults
也是如此。所以你的代码应该看起来像这样。
$json = json_decode($resp, true);
foreach ($json['VehicleResults'] as $item)
{
$dataItems = $item['FinanceProductResults'];
foreach ($dataItems as $data) {
$v0 = $data['Term'];
foreach ($data['ProductResults'] as $productResult) {
$type = $productResult['Key'];
$payment = $productResult['Payment'];
echo "Term: $v0, Type: $type, Payment: $payment";
}
}
}