douli1854 2016-06-02 20:17
浏览 94
已采纳

PHP - 如何检查空数组?

Ok, this is easy, but I don't know why mine is not checking it!

I have an if statement that checks if an array is empty, if it's empty it should skip it, but all tries made not to skip it.

Here is the code:

$quizCounter = 0;
foreach ($quizzes as $key => $quiz) {

    if (!is_null($quiz['quiz_data'])) {

        echo "---->" . $key . "<BR>";

        unset($mark);
        $result = 0;
        $quizData = unserialize($quiz['quiz_data']);
        $quizTimestamp = date("d-m-Y", strtotime($quiz['time_stamp']));

        echo "Quiz: ";
        var_dump($quiz);
        echo "<BR>";

        echo "Quiz Data: ";
        var_dump($quizData);
        echo "<BR>";

        echo "Var Dump: ";
        var_dump($quizData['marks']);
        echo "<BR>";

        // Quiz marks
        if(!empty($quizData['marks'])) {
            foreach ($quizData['marks'] as $key => $marks) {
                $mark[$key] = $marks;
                echo "Mark: ";
                echo var_dump($marks) . "<BR>";
                $result += $marks;
            }
        }

        $markCounter = (count($mark) == 0) ? 1 : count($mark);
        $quizResult[$quizCounter] = $result / $markCounter;
        $quizCounter++;

    }

}

And here is the result that I need to skip:

---->34
Quiz: array(4) { ["quiz_data"]=> string(41) "a:2:{s:4:"ques";a:0:{}s:5:"marks";a:0:{}}" [0]=> string(41) "a:2:{s:4:"ques";a:0:{}s:5:"marks";a:0:{}}" ["time_stamp"]=> string(26) "0000-00-00 00:00:00.000000" [1]=> string(26) "0000-00-00 00:00:00.000000" } 
Quiz Data: array(2) { ["ques"]=> array(0) { } ["marks"]=> array(0) { } } 
Var Dump: array(0) { } 

How may I skip this array?

  • 写回答

1条回答 默认 最新

  • dongtuo5262 2016-06-02 21:23
    关注

    The following things are considered to be empty:

    "" (an empty string)
    0 (0 as an integer)
    0.0 (0 as a float)
    "0" (0 as a string)
    NULL
    FALSE
    array() (an empty array)
    $var; (a variable declared, but without a value)
    

    This is a quote from the following page:

    http://php.net/manual/en/function.empty.php

    The reason why your code considers $quizData['marks'] as empty is because you have a variable equal to zero in $quizData['marks']. If you add another value that is not zero, your code should work.

    Perhaps consider adding:

    else if(isset($quizData['marks'])) {
        //proceed to print that person has a mark of zero
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!