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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?
  • ¥50 cocos2d-x lua 在mac上接入lua protobuf?