user2487040
user2487040

Reputation: 13

Transpose a SimpleXMLElement object containing arrays

I have this array:

SimpleXMLElement Object
(
[id] => Array
    (
        [0] => Koala.jpg
        [1] => Jellyfish.jpg
    )

[desc] => Array
    (
        [0] => koaladesc
        [1] => jelly desc
    )

[qtidade] => Array
    (
        [0] => 1
        [1] => 5
    )

I need create some php function that help me group the values like this:

[0] => Array
    (
        [0] => Koala.jpg
        [1] => koaladesc
        [2] => 1
    )

[1] => Array
    (
        [0] => Jellyfish
        [1] => jelly desc
        [2] => 5
    )

Could anyone help me?

Upvotes: 0

Views: 89

Answers (3)

faino
faino

Reputation: 3224

Something like this should do the trick, but it's localized to what you're asking based on the vagueness of your question:

$new_array = array();
foreach($simple_xml_object as $obj) {
    if(is_array($obj)) {
        for($i = 0; $i < count($obj); $i++) {
            $new_array[$i][] = $obj[$i];
        }
    }
}

I would suggest looking at the documentation on the foreach() construct, as well as looking over the SimpleXML manual.

Upvotes: 2

Mudasir Nazir
Mudasir Nazir

Reputation: 59

let's suppose your array is saved in variable $arrayValues

$arrayValues = [id] => Array
(
    [0] => Koala.jpg
    [1] => Jellyfish.jpg
)

[desc] => Array
(
    [0] => koaladesc
    [1] => jelly desc
)

[qtidade] => Array
(
    [0] => 1
    [1] => 5
)

now you need to create the following code:

foreach($arrayValues as $array)
{
    echo $array->id;
    echo $array->desc;
    echo $array->qtidade;
}

this may work well for you.

Upvotes: 0

Andrew Cheong
Andrew Cheong

Reputation: 30273

So, you want to tranpose an array. Here's a magical way of transposing rectangular arrays:

array_unshift($array, null);
$array = call_user_func_array('array_map', $array);

Upvotes: 1

Related Questions