如何在PHP中打印元素数目未知的数组
我在打印数组的元素时遇到了一个非常奇怪的问题 我试图打印出php foreach中数组的一些元素,这里就是数组的样子如何在PHP中打印元素数目未知的数组,php,mysql,Php,Mysql,我在打印数组的元素时遇到了一个非常奇怪的问题 我试图打印出php foreach中数组的一些元素,这里就是数组的样子 [2] => Array ( [id] => 3 [body] => dsfgdfgd [has_subquestion] => 1 [is_subquestion] => 0 [ordering] => 2
[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
)
)
注意,第一个有2个[sub],第二个只有一个。这是我打印它们的代码
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;
回声计数($question['sub']);
foreach($s形式的问题['sub']):
回声'8您需要更新代码以查看[sub]数组是否为多维数组。我会通过检查sub是否有一个仅在只有一个数组时匹配的键来实现:
if (array_key_exists('id', $question['sub']) {
// This is a single array so wrap it in an array so that the foreach logic works
$question['sub'] = array($question['sub']);
}
... continue as normal with your foreach loop.
使用is_array()并递归调用函数?运行
打印($array)
它还应该以递归方式为您提供答案是否有另一个foreach(或其他循环)包含您发布的内容?谢谢,这是我需要的。我想再问一个问题。当我执行var_dump($_POST['sub'])时,唯一保存的是最后一个。如何使sub[id]保存多个id?O尝试了name=“sub[][id]”和name=“sub[id][]”两种方法,但均无效。我猜我需要找到一种不同的方法来保存2个隐藏的输入。