2012-04-03 49 views
0

請原諒我的標題(heh)中的雙關語,但這真是讓我瘋狂! 這是我的代碼:驅動我的循環陣列(y)

for ($i=0;$i < $a;$i++){ 

    $total = (array)$orders -> Total -> Line[$i]; 

    echo '<pre>'; 
    print_r($total); 
    echo '</pre>'; 
} 

...它輸出以下:

Array 
(
    [@attributes] => Array 
     (
      [type] => Subtotal 
      [name] => Subtotal 
     ) 

    [0] => 299.99 
) 

Array 
(
    [@attributes] => Array 
     (
      [type] => Shipping 
      [name] => Shipping 
     ) 

    [0] => 13.36 
) 

Array 
(
    [@attributes] => Array 
     (
      [type] => Tax 
      [name] => Tax 
     ) 

    [0] => 0.00 
) 

Array 
(
    [@attributes] => Array 
     (
      [type] => GiftCertificate 
      [name] => Gift certificate discount (117943:@CAC7HXPXFUNNJ3MTGC:63.35 117372:@DK9T9TMTCTCTUWF9GC:250.00) 
     ) 

    [0] => -313.35 
) 

Array 
(
    [@attributes] => Array 
     (
      [type] => Total 
      [name] => Total 
     ) 

    [0] => 0.00 
) 

我的問題是:我怎麼保存根據[0]進入相應的變量命名每個金額陣列[ '類型']?

+0

這是從'SimpleXML'元素? – 2012-04-03 20:22:04

+0

是的搖滾......爲什麼?作爲一個對象會更好嗎? – bobbiloo 2012-04-03 20:23:20

+0

你能顯示原始的XML嗎?可以使用'foreach'迭代SimpleXML元素,而不將其轉換爲數組。 – 2012-04-03 20:43:14

回答

0

$var[] = array('type' => $total['@attributes']['type'], 'amount' => $total[0])

0

像這樣的事情可能?

$total_amount_by_type = array(); 
for ($i=0;$i < $a;$i++){ 

    $total = (array)$orders -> Total -> Line[$i]; 

    $total_amount_by_type[$total->type] = $total[0] 

} 
3

而不是可變(其可以具有可變的變量來完成),我建議將它們放入一個數組$prices,由type屬性鍵控。

$prices = array(); 
for ($i=0;$i < $a;$i++){ 

    $total = (array)$orders -> Total -> Line[$i]; 

    echo '<pre>'; 
    print_r($total); 
    echo '</pre>'; 

    // Append the price to an array using its type attribute as the 
    // new array key 
    $prices[$total['@attributes']['type']] = $total[0]; 
} 

當然未經測試,但我相信它會完成這項工作。

0

你在找什麼東西like this

for ($i=0;$i < $a;$i++){ 
    $total = (array)$orders -> Total -> Line[$i]; 

    // will create variables $Tax, $GiftCertificate etc 
    ${$total['@attributes']['type']} = $total[0]; 

    echo '<pre>'; 
    print_r($total); 
    echo '</pre>'; 
}