如何使用未知数量的元素在PHP中打印数组

时间:2013-01-09 19:20:34

标签: php mysql

打印出数组元素时遇到一个非常奇怪的问题。

我试图在php foreach中打印出一些数组元素。这正是数组的样子

 [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;

这就是它的印刷

2 dfgdfg gsdgdf

8&lt; - 计数(应该是1而不是8) 6&lt; - 以下每个是子阵列中的第一个字母/数字 d 0 1 3 0 2

谁能看到我做错了什么?

3 个答案:

答案 0 :(得分:1)

运行 的print_r($数组)。

它也应该以递归的方式给你答案

答案 1 :(得分:0)

您需要更新代码以查看[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.

答案 2 :(得分:0)

使用is_array()并以递归方式调用函数?