开发者

Convert multi-dimensional multi-object array to standard multi-dimensional array in PHP

I have a multi-dimensional mul开发者_Go百科ti-object array from a simplexml_import_dom() function call.

A slice of one section of the array:

[Price] => SimpleXMLElement Object
(
    [Prices] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [MType] => A
                            [PType] => R

This is causing me quite a bit of problems when trying to read nested objects. I have tried to loop through the array using multiple get_object_vars() but because the depth and location of the nested objects is continually changing I haven't been able to yield desirable results.

Does PHP contain a function that I haven't been able to find to convert a multi-dimensional multi-object array to a standard multi-dimensional array? Or has anyone solved this problem before?

Thanks for your help!


The question is often asked, but there's a fundamental issue that has to be addressed on a case-by-case basis when converting a XML tree to an array, which makes an one-size-fits-all method impossible: how do you differentiate nodes from attributes?

For instance, how would you convert this XML to an array:

<node val="attr"><val>child</val></node>

Also, a node can have any number of children with the same name, which you can't emulate with an associative array.

Long story short, you'll have to cook up your own solution. Judging from your output, it would look something like this:

$arr = array();
foreach ($Price->Prices as $Prices)
{
    $tmp = array();

    foreach ($Prices->attributes() as $k => $v)
    {
        $tmp[$k] = (string) $v;
    }

    $arr[] = $tmp;
}

If it's not what you're looking for, please edit your question and add an example of the source document (XML) as well as the expected result (the array.)


Are you aware that these objects have functions that you can use? Try the following:

foreach ($simpleXmlObject->children() as $element) {
    echo $element->getName();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜