Search code examples
cakephpcakephp-2.4cakephp-2.4.7

Using Hash::extract() on Array from Xml


I have an array as follows:

array(
    'items' => array(
        'item' => array(
            (int) 0 => array(
                '@item' => '3-394-001068-00000'),
            (int) 1 => array(
                '@item' => '3-394-001069-00000'),
            )
     )
)

I am trying to extract all the 'item' entries to a new array.

Here is my code so far:

$xmlarray = Xml::toArray(Xml::build(WWW_ROOT .'files/itemsAll/'.$file));

            debug($xmlarray);
            $results = Hash::extract($xmlarray, '{n}.item');

            debug ($results);

but this returns only an empty array. Could someone maybe give me a hint where I'm going wrong?

thanks in advance


Solution

  • It isn't crystal clear from your question, but I assume this array

    array(
        'items' => array(
            'item' => array(
                (int) 0 => array(
                    '@item' => '3-394-001068-00000'),
                (int) 1 => array(
                    '@item' => '3-394-001069-00000'),
    

    is the result of your debug($xmlarray);, so we can rule out misslocation of a file (if I'm assuming wrong, do tell).

    So, the hash is your problem.

    See, according to docs, the {n} refers to "a numeric key", and "items" is clearly not. If you want to extract all "item" inside "items", it should be

    Hash::extract($xmlarray, 'items.item');
    

    and that will give you

    array((int) 0 => array(
                    '@item' => '3-394-001068-00000'),
                (int) 1 => array(
                    '@item' => '3-394-001069-00000'),
    /*etc*/
    

    and, if you want to have a much compact array (don't know if you need the index associations), you could try

    Hash::extract($xmlarray, 'items.item.{n}.@item');
    

    and that'll get you

    array('3-394-001068-00000', '3-394-001069-00000')