PHP ForEach循环不迭代/计数

时间:2014-04-26 16:17:58

标签: php android json web-services foreach

我正在尝试使用Web服务以JSON格式将值返回到Android应用程序。出于某种原因,我的代码只返回“无效登录,请再试一次”。我很肯定正在输入用户名,我很肯定任务正在正常返回。使用我作为注释行包含的测试代码,验证服务将向应用程序返回一组数据。似乎问题出在我的foreach循环中,但我不知道如何。这很简单。显然它不是迭代,或者我的计数会增加,我不会收到无效登录错误。我唯一可以想到的是我需要使用一个嵌套的foreach循环,但我也没有取得太大的成功。

先谢谢你的帮助,伙计们!

这是foreach循环...

//for reach task returned, add to array for later output
            foreach ($row2['Description'] as $t)
            {
            $taskDisplay = array('task' => $t);
            $taskCount++;
            }

和计数...

if ($taskCount > 0)    
{
echo json_encode($taskDisplay);
}
else
{
echo "Invalid login, please try again";
}

这里是完整的代码

$taskDisplay = array();
$taskCount = 0;

//do this portion if app gives key value "PART_ONE"
if ($result['part'] == "PART_ONE")

{   
    //if username was entered, check user credentials
    if(array_key_exists('user', $result)) {

        $usercheck = $con->prepare("Select * from Employee
                        Where usr = ?
                        and pass = ?");
        $usercheck -> execute(array($result['user'], $result['password']));
        $row = $usercheck -> fetch();

        //if username was verified, select tasks from database
        if($row['usr'])
        {

            $task = $con->prepare("Select * from Tasks
                        where Assigned_Employee = ?");
            $task -> execute(array($result['user']));
            $row2 = $task -> fetch();
            $statusCode = "Success";
            //$taskDisplay = $row2['Description'];

            //for reach task returned, add to array for later output
            foreach ($row2['Description'] as $t)
            {
            $taskDisplay = array('task' => $t);
            $taskCount++;
            }   

        }


    else
    {
    $statusCode = "Fail";
    //bail if invalid username entered
    exit;
    }


    //$arr = array('task' => $taskDisplay, 'status_code' => $statusCode);
    //echo json_encode($arr);

    if ($taskCount > 0) 
    {
    echo json_encode($taskDisplay);
    }
    else
    {
    echo "Invalid login, please try again";
    }

}
}

1 个答案:

答案 0 :(得分:0)

foreach所有您想要fetchAll()的行。然后,您想要访问每行中的Description列:

$row2 = $task->fetchAll();

// etc...

foreach ($row2 as $t)
{
    $taskDisplay[] = array('task' => $t['Description']);
    $taskCount++;
}