【发布时间】:2014-10-06 17:30:53
【问题描述】:
我目前正在为我的网站开发搜索功能,并以 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);
}
知道为什么会这样吗?是我如何迭代循环还是设置?我确信我忽略了一些简单的东西,但我无法弄清楚它是什么。
【问题讨论】:
-
您确定
$results在json_encode之前不为空吗? -
不相关,但要生成有效的 json,您需要将最后一条语句放在
while循环之外(以防有超过 1 个结果)。
标签: php json for-loop mysqli while-loop