数组驱动我循环(y)


Array driving me loop(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]保存到根据数组['type']命名的相应变量中?

我建议将它们放入由type属性键控的数组$prices中,而不是一个变量(可以用变量变量来完成)。

$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];
}

当然,没有经过测试,但我相信它会完成任务。

$var[] = array('type' => $total['@attributes']['type'], 'amount' => $total[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]
}

你在寻找这样的东西吗:

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>';
}