2014-10-06 115 views
1

我目前正在为我的网站搜索功能,并以JSON返回结果。然而,一些值返回第一个结果等之后,返回以下:PHP:JSON返回NULL值

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

任何想法为什么会发生这种情况?它是如何迭代循环或设置?我确信我忽略了一些简单的东西,但我无法弄清楚它是什么。

+0

你确定'$ results'在'json_encode'之前不是null吗? – 2014-10-06 17:40:34

+0

不相关,但为了生成有效的json,您需要将最后一个语句放在'while'循环之外(以防万一出现多个结果)。 – jeroen 2014-10-06 17:55:40

+0

感谢您的提示! – user1502224 2014-10-06 18:23:36

回答

1

的问题是要覆盖在内环您$row变量:将使用您上次内的最后结果

​​

所以如果$max超过1,从你的第二次迭代循环。这不会是您所期望的查询结果。

+1

好的!解决了我的问题,谢谢! – user1502224 2014-10-06 18:23:21