1
我正在處理一個API,當有多個項目時返回一個數字索引數組,但不存在單個項目時。從數組索引有時數字索引,有時不是
以下是響應中有多個項目時返回的內容。
array(
'LineItem' => array(
(int) 0 => array(
'Description' => 'Advanced SEO programme',
'UnitAmount' => '90.00',
'TaxType' => 'OUTPUT2',
'TaxAmount' => '18.00',
'LineAmount' => '90.00',
'AccountCode' => '223',
'Tracking' => array(
'TrackingCategory' => array(
'Name' => 'Client',
'Option' => 'G&Ts World of Cards',
'TrackingCategoryID' => 'ae873c49-da89-42a5-8955-d269c5bd2dcd'
)
),
'Quantity' => '1.0000'
),
(int) 1 => array(
'Description' => 'Advanced Links programme',
'UnitAmount' => '125.00',
'TaxType' => 'OUTPUT2',
'TaxAmount' => '25.00',
'LineAmount' => '125.00',
'AccountCode' => '223',
'Tracking' => array(
'TrackingCategory' => array(
'Name' => 'Client',
'Option' => 'G&Ts World of Cards',
'TrackingCategoryID' => 'ae873c49-da89-42a5-8955-d269c5bd2dcd'
)
),
'Quantity' => '1.0000'
)
)
)
這裏是當只有一個單一的項目返回什麼返回:
array(
'LineItem' => array(
'Description' => 'Monthly office IT support (Email, file system and printer)',
'UnitAmount' => '95.00',
'TaxType' => 'OUTPUT2',
'TaxAmount' => '19.00',
'LineAmount' => '95.00',
'AccountCode' => '221',
'Tracking' => array(
'TrackingCategory' => array(
'Name' => 'Client',
'Option' => 'Naturewood Flooring Company Ltd',
'TrackingCategoryID' => 'ae873c49-da89-42a5-8955-d269c5bd2dcd'
)
),
'Quantity' => '1.0000'
)
)
這就是我想做的事:
foreach ($response['LineItem'] as $line) {
$invoices['Lineitem'][] = array(
'description' => $line['Description'],
'amount' => $line['LineAmount'],
'account' => $line['AccountCode'],
'client' => $line['Tracking']['TrackingCategory']['Name']
);
}
T當單個項目返回時,他不工作,我得到一個索引找不到錯誤。
我目前的解決辦法是這樣的:
if(isset($response['LineItem'][0])){
foreach ($response['LineItem'] as $line) {
//debug($line);
$invoices['Lineitem'][] = array(
'description' => $line['Description'],
'amount' => $line['LineAmount'],
'account' => $line['AccountCode'],
'client' => $line['Tracking']['TrackingCategory']['Name']
);
}
} else {
$invoices['Lineitem'][] = array(
'description' => $response['LineItem']['Description'],
'amount' => $response['LineItem']['LineAmount'],
'account' => $response['LineItem']['AccountCode'],
'client' => $response['LineItem']['Tracking']['TrackingCategory']['Name']
);
}
但我不認爲這是去了解它的最佳方式。有更好,更乾淨的方法嗎?
太好了,謝謝! –