如何通过键名检索json子数组值

时间:2014-04-08 05:23:39

标签: php mysql arrays json

我一直在尝试为我的json数组找到正确的代码,该代码来自mysql数据库。 所以要清楚,让我先发布代码。

json数组(来自下面的php代码)

{"query":"han","user_info":[{"username":"HannaShissler"},{"avatar":"\/\/en.wetube.org\/tubes\/uploads\/avatar\/no_avatar.png-50"},{"username":"Athanh"},{"avatar":"\/\/en.wetube.org\/tubes\/uploads\/avatar\/no_avatar.png-50"},{"username":"sabhan"},{"avatar":"\/\/en.wetube.org\/tubes\/uploads\/avatar\/no_avatar.png-50"}]}

PHP

$search_sql = $db->query("SELECT * FROM users WHERE username like '%$query%' order by id DESC LIMIT 5");        
$data = array();
while($array = $db->fetch_assoc($search_sql)){
    $data[]['username'] = $array['username'];
    $data[]['avatar'] = DOMAIN.TUBES.UPLOADS.AVATAR.resizer($array['avatar'],'50','');
}
$data = array(
'query'=>$query,
'user_info'=>$data
);

echo json_encode($data);

JS / AJAX / JSON

success: function(data){

$.each(data.user_info, function(index,value) {
    alert(value.username);
  }); 

}

现在我想要获得的是user_info子数组的用户名。 如果有另一种重写PHP代码的方法,因为我觉得我做错了。 请帮助这些人,我依赖你。或者我将不得不回到html而不是json数据:(

1 个答案:

答案 0 :(得分:2)

我会改变

{"username":"HannaShissler"},{"avatar":"\/\/en.wetube.org\/tubes\/uploads\/avatar\/no_avatar.png-50"}

{"username":"HannaShissler","avatar":"\/\/en.wetube.org\/tubes\/uploads\/avatar\/no_avatar.png-50"}

(每个用户一个对象,而不是将头像和用户名放在不同的对象中)

执行此操作的代码将是

$search_sql = $db->query("SELECT * FROM users WHERE username like '%$query%' order by id DESC LIMIT 5");        
$data = array();
while($array = $db->fetch_assoc($search_sql)){
    $data[]=array(
        'username' => $array['username'];
        'avatar' => DOMAIN.TUBES.UPLOADS.AVATAR.resizer($array['avatar'],'50','')
    );
}
$data = array(
'query'=>$query,
'user_info'=>$data
);

echo json_encode($data);