2

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

我正在尝试在 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 <--count (应该是 1 而不是 8) 6 <--以下每个都是子数组中的第一个字母/数字 d 0 1 3 0 2

谁能看到我做错了什么?

4

3 回答 3

1

运行 print_r($array)。

它还应该以递归方式为您提供答案

于 2013-01-09T20:00:46.720 回答
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.
于 2013-01-09T19:26:12.333 回答
0

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

于 2013-01-09T19:37:33.110 回答