繁体   English   中英

PHP:JSON返回空值

[英]PHP: JSON Returning NULL Values

我目前正在为我的网站开发搜索功能,并以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提取期间填充这些字段,我有几个循环:

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);
}

知道为什么会这样吗? 这是我在循环或设置中进行迭代的方式吗? 我敢肯定,我忽略了一些简单的东西,但是我无法弄清楚它是什么。

问题是您在内部循环中覆盖了$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,则从第二次迭代开始,您将使用上一个内部循环的最后一个结果。 这将不是您期望的查询结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM