Reputation: 1
//this is my mysql result
$search_result=$this->Connect_user_model->get_user($key_word);
$info=array();
foreach($search_result as $row){
$info[]=array('username' => $row->username,
'email' => $row->email,
'gender' => $row->gender);
echo json_encode($info);'
}
how can i loop this response? i get responce like--
0: {
username: iamanam,
email: 1,
gender: Male
}
email: "1"
gender: "Male"
username: "iamanam"
1: {
username: admin,
email: [email protected],
gender: Male
}
email: "[email protected]"
gender: "Male"
username: "admin"
2: {
username: iamanam,
email: [email protected],
gender: Male
}
email: "[email protected]"
gender: "Male"
username: "iamanam"
when i echo json_encode outside loop.it works but i got each result double i use this function for loop ----
function process_response(data){
var show_user='';
$.each(data,function(contact,contactInfo) {
show_user+='<div class="discounted-item '+contactInfo.gender+' music-playlist">';
show_user+='<img src="" alt="" class="music-playlist-left" width="38px" height="38px" />';
show_user+='<h1>';
show_user+=contactInfo.username;
show_user+='</h1>';
show_user+='<p>';
show_user+= contactInfo.gender;
show_user+='</p>';
show_user+='<a href="" title="" class="tips" rel="">';
show_user+='<img src="" alt="f" class="music-playlist-right" id="img"></a>';
show_user+='</div>';
}); // end of each()
// add finished HTML to page
$('#info').append(show_user);
}//process_responce
Upvotes: 0
Views: 250
Reputation: 168685
What you're doing wrong is outputting the JSON in a loop.
This means that your output is actually several separate JSON blocks: If you're trying to read that output as a single JSON block, it won't work.
What you need to do is build it all into an array, and output the JSON after you've finished looping the array.
Since you're already building the $info[]
array correctly, all you need to do to fix your code it move the echo
outside the foreach
loop, as follows:
foreach($search_result as $row){
$info[]=array('username' => $row->username,
'email' => $row->email,
'gender' => $row->gender);
}
echo json_encode($info);
Hope that helps.
By the way, if $row
contains only those three fields, it's worth knowing that json_encode()
is capable of encoding an object just as easily as an array. So if $row
is just those three fields, then you could simply do $info[]=$row;
inside the loop, and the output at the end will be the same.
Upvotes: 2
Reputation: 4111
Do you actually mean the echo out the JSON string each time you iterate through the results? If you move the echo statement out of the for loop you'll get one JSON object with all of your data, rather than getting the JSON object each time data is added.
Upvotes: 2