Array Reference Question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JackD
Forum Commoner
Posts: 62
Joined: Sat Dec 12, 2009 6:25 pm

Array Reference Question

Post by JackD »

pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


The following code handles multiple array elements but fails when there is only one element:

Code: Select all

   $parsed_xml = simplexml_load_string($Response); //'<Items><Item>..</Item><Item>..</Item><Item>..</Item></Items>'
    $A = (array)$parsed_xml->Items;   // loads single or multiple entries correctly
    $Item = (array)$A['Item'];            // loads multiple entries correctly, fails on single entries because it omits
                                                  // object(SimpleXMLElement) as part of the returned array
                                                  // $Item = (array)$A->Item;    does not work with following code
    if ($Item[0]) // single entries do not have numeric keys (0, 1, 2, etc.) so this test will fail for single entries
    { foreach ($Item as $i=>$Item_Data)  
        { $EAN = $Item_Data->ItemAttributes->EAN;     // gets correct value from multiple entries
          display_item($Item_Data);  // different array format is passed than below
             }
    }
      else      // this form must be used to get the correct value when there is only a single entry in $Item
       { $EAN = $Item['ItemAttributes']->EAN;   // gets correct value from single entry
      display_item($Item);  // display_item fails because of missing "object(SimpleXMLElement)" 
    }
What am I doing wrong and why do the following two array references return different values?

echo $Item->ItemAttributes->EAN . "<br />"; // returns null for single entry
echo $Item['ItemAttributes']->EAN . "<br />"; // returns correct value for single entry


pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.
Post Reply