Array Reference Question
Posted: Fri Jan 01, 2010 11:10 pm
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:
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:
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:
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)"
}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: