The following is a print_r of an array converted from an XML document:
Array
(
[layer1] => Array
(
[item] => Array
(
[item-id] => 1886731
[item-name] => Bad Dog
[category] => pets
[link] = http://www.baddog.com/
)
[total-matched] => 1
)
)
For the above array, sizeof($myarray[layer1][item]) should return 1, but it returns 4. I get the correct number of “item” items if there are more than one of them. The same error happens regardless of whether I use “sizeof” or “count”. How do I get PHP to return “1” when there is only one item?
Consequently, if there is one item, I can’t access item-name using array[layer1][item][0][item-name], I have to use array[layer1][item][item-name].
There is a world of difference between:
and:
Basically they are different structures, and PHP is correct to return the following:
If you wish to get a count for
['layer1']['item']that makes sense to your app, you will always need['layer1']['item']to be an array containing multiple array structures… i.e. like$array1above. This is the reason why I ask what is generating your array structure because – whatever it is – it is basically intelligently stacking your array data depending on the number of items, which is something you don’t want.Code that can cause an array to stack in this manner normally looks similar to the following:
Basically if you keep calling the above code, and tracing after each run, you will see the following structure build up:
then
then
It’s the first step in this process that is causing the problem, the
$array = 'value';bit. If you modify the code slightly you can get rid of this:As you can see all I’ve done is delete the itermediate
if statement, and made sure when we discover no initial value is set, that we always create an array. The above will create a structure you can always count and know the number of items you pushed on to the array.then
then
update
Ah, I thought so. So the array is generated from XML. In this case I gather you are using a predefined library to do this so modifying the code is out of the question. So as others have already stated, your best bet is to use one of the many XML parsing libraries available to PHP:
http://www.uk.php.net/simplexml
http://www.uk.php.net/dom
When using these systems you retain more of an object structure which should be easier to count. Both the above also support xpath notation which can allow you to count items without even having to grab hold of any of the data.
update 2
Out of the function you’ve given, this is the part that is causing your arrays to stack in the manner that is causing the problem:
The modification would be:
That should stop your arrays from stacking… however if you have any other part of your code that was relying on the previous structure, this change may break that code.