-3

I have specific array that I cant find way to distinguish if it has multiple entries or single entry because when it has multiple entries I get

Multiple entries array

And when I get single entry I dont get [0] as first entry instead I get this

Single entry array

Im using foreach loop in php to extract data from array, but when it returns single item in array, it loops 3 times for each item in array :categoryid, name and other instead once and then, of course I get error

Warning: Illegal string offset 'CategoryID' Warning: Illegal string offset 'Name'

How can I check if its single item or multiple items?

Code :

foreach($obj["Store"]["CustomCategories"]["CustomCategory"]as $category=>$val)
{
echo "<a href=\"#\" onclick=getCategory(\"";
echo $obj["Store"]["Name"];
echo "\",";
echo $val["CategoryID"];
echo ",1";
echo ");>";
echo $val["Name"];
echo "</a>"; 
}    
perkes456
  • 1,163
  • 4
  • 25
  • 49

1 Answers1

1

You can test whether CustomCategory contains is an indexed or associative array by checking for an element with index 0. If not, you can wrap the contents in an array and then do your foreach loop.

$customCategory = $obj["Store"]["CustomCategories"]["CustomCategory"];
if (!$customCategory[0]) {
    $customCategory = array($customCategory);
}
foreach ($customCategory as $category => $val) {
    ...
}
Barmar
  • 741,623
  • 53
  • 500
  • 612