Array driving me loop(y)

Go To StackoverFlow.com

0

Pardon the pun in my title (heh) but this is seriously driving me nuts! This is my code:

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

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

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

...It outputs the following:

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
)

My question is: how do I save each dollar amount [0] into a respective variable named according to the array['type']?

2012-04-03 20:17
by bobbiloo
Is this from a SimpleXML element - Rocket Hazmat 2012-04-03 20:22
Yes Rock...why? Would it be better off as an object - bobbiloo 2012-04-03 20:23
Can you show the original XML? SimpleXML elements can be iterated over using foreach without converting it to an array - Rocket Hazmat 2012-04-03 20:43
Hi Rocket, thanks for the help. I ended up using a form of David Nguyen's solution -- it gave me the most control - bobbiloo 2012-04-04 13:27


0

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

2012-04-03 20:21
by David Nguyen


3

Rather than a variable (which could be done with variable variables), I recommend putting them into an array $prices, keyed by the type attributes.

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

Untested, of course, but I believe it will do the job.

2012-04-03 20:22
by Michael Berkowski


0

Something like this maybe?

$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-03 20:22
by Deleteman


0

Are you looking for something 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>';
}
2012-04-03 20:27
by anubhava
Ads