0

请原谅我标题中的双关语(呵呵),但这真的让我发疯了!这是我的代码:

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

4 回答 4

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

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

于 2012-04-03T20:22:58.163 回答
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]

}
于 2012-04-03T20:22:51.013 回答
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>';
}
于 2012-04-03T20:27:52.853 回答
0

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

于 2012-04-03T20:21:59.197 回答