I am having a very strange issue with printing out element of an array.
I am attempting to print out some elements of an array inside of a php foreach Here is exactly what the array looks like
[2] => Array
(
[id] => 3
[body] => dsfgdfgd
[has_subquestion] => 1
[is_subquestion] => 0
[ordering] => 2
[is_manditory] => 0
[created] => 2013-01-09 12:06:47
[parent_id] => 0
[sub] => Array
(
[0] => Array
(
[id] => 4
[body] => dfgdfg
[has_subquestion] => 1
[is_subquestion] => 1
[ordering] => 0
[is_manditory] => 0
[created] => 2013-01-09 11:24:20
[parent_id] => 3
)
[1] => Array
(
[id] => 23
[body] => gsdgdf
[has_subquestion] => 1
[is_subquestion] => 1
[ordering] => 14
[is_manditory] => 0
[created] => 2013-01-09 12:56:33
[parent_id] => 3
)
)
)
[3] => Array
(
[id] => 5
[body] => dfgdfg
[has_subquestion] => 1
[is_subquestion] => 0
[ordering] => 3
[is_manditory] => 0
[created] => 2013-01-09 12:06:47
[parent_id] => 0
[sub] => Array
(
[id] => 6
[body] => dfgdfg
[has_subquestion] => 0
[is_subquestion] => 1
[ordering] => 3
[is_manditory] => 0
[created] => 2013-01-08 13:37:07
[parent_id] => 5
)
)
Notice that the first one has 2 [sub]’s and the second only has one. This is my code for printing them
echo count($question['sub']);
foreach($question['sub'] as $s):
echo '<li>
<input type="hidden" name="sub[id]" value="'. $s['id'] .'" />
<input type="hidden" name="sub[parent]" value="'. $question['id'] .'" />
'. $s['body'] .'</li>';
endforeach;
this is what it is printing
2
dfgdfg
gsdgdf
8 <–count (which should be 1 not 8)
6 <–each of the following are the first letter/number in the sub array
d
0
1
3
0
2
Can anyone see what I am doing wrong?
You will need to update your code to see if the [sub] array is multidimensional or not. I would do it by checking if sub has a key that will only match if there is only a single array: