数组驱动我循环(y)

时间:2012-04-03 20:17:46

标签: php arrays loops

原谅我头衔中的双关语(嘿),但这严重让我疯了! 这是我的代码:

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']命名的相应变量中?

4 个答案:

答案 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];
}

当然没有经过测试,但我相信它会完成这项工作。

答案 1 :(得分:0)

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

答案 2 :(得分: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 :(得分: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>';
}