PHP: JSON Returning NULL Values


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,那么从第二次迭代开始,您将使用上一次内部循环的最后一个结果。这将不是您期望的查询结果。