PHP:JSON返回NULL值

时间:2014-10-06 17:30:54

标签: php json for-loop mysqli while-loop

我目前正在为我的网站开发搜索功能,并以JSON格式返回结果。但是,在返回第一个结果后会返回一些值,如下所示:

{"fullname":"test name","occupation":"test","industry":"testing","bio":"i am testing stuff.","gender":"f","website":"http:\/\/yhisisasite.com","skills":["writing","reading","math","coding","baseball"],"interests":["coding","sampling","googling","typing","playing"]},{"fullname":null,"occupation":null,"industry":null,"bio":null,"gender":null,"website":null,"skills":["coding","docotrs","soeku","spelling"],"interests":["testing","wintro","skating","hockey","code"]}

我目前有一个类作为结果的模板,如下所示:

class SearchResultUserProfile {
    public $fullname = "";
    public $occupation = "";
    public $industry = "";
    public $bio = "";
    public $gender = "";
    public $website = "";
    public $skills = array();
    public $interests = array();

}

然后在mysqli fetch中填充那些字段我有几个循环:

while ($row = mysqli_fetch_array($result))
{   
    $max = sizeof($user_id_array);
    for($i = 0; $i < $max; $i++)
    {
    //create a new instance or object
    $searchResultUserProfile = new SearchResultUserProfile();
    $searchResultUserProfile->fullname = $row['fullname'];
    $searchResultUserProfile->occupation = $row['occupation'];
    $searchResultUserProfile->industry = $row['industry'];
    $searchResultUserProfile->bio = $row['bio'];
    $searchResultUserProfile->gender = $row['gender'];
    $searchResultUserProfile->website = $row['website'];

    //grab the interests and skills
    $skillDetails = fetchAllUserSkills($user_id_array[$i]);
    foreach($skillDetails as $row) {
        $thistest = $row['skills'];
        array_push($searchResultUserProfile->skills, $thistest);
    }

    $interestDetails = fetchAllUserInterests($user_id_array[$i]);
    foreach($interestDetails as $row) {
        $thistests = $row['interests'];
        array_push($searchResultUserProfile->interests, $thistests);
    }
    array_push($results, $searchResultUserProfile);

    }
    echo json_encode($results);
}

知道为什么会这样吗?是我如何迭代循环或设置?我确信我忽略了一些简单但我无法弄清楚它是什么。

1 个答案:

答案 0 :(得分:1)

问题是你在内部循环中覆盖了$row变量:

while ($row = mysqli_fetch_array($result))
       ^^^^ this is a result row from your query
{   
    $max = sizeof($user_id_array);
    for($i = 0; $i < $max; $i++)
    {
        $searchResultUserProfile = new SearchResultUserProfile();
        $searchResultUserProfile->fullname = $row['fullname'];

        ...

        foreach($skillDetails as $row) {
                                 ^^^^ here you are overwriting your query result
           ...
        }

        ...

    }
    echo json_encode($results);
}

因此,如果$max大于1,则从第二次迭代开始,您将使用上一个内循环的最后一个结果。而这不是您期望的查询结果。