Reputation: 261
I'm having some troubles with a multidimensional array. My php code is as follows:
$result = array();
$count = 0;
foreach($matches_lines as $lines){
$match_user = $lines["signup_username"];
$match_birth = $lines["signup_birth"];
$match_city = $lines["signup_city"];
$match_gender = $lines["signup_gender"];
$match_os = $lines["signup_os"];
$match_persontype = $lines["signup_persontype"];
if("some check on the variables"){
$result[$count] = array('username' => "$match_user", 'birth'=> "$match_birth", 'city' => "$match_city", 'gender' => "$match_gender", 'os' => "$match_os", 'persontype' => "$match_persontype");
$count = $count + 1;
}
}
}
echo json_encode($result);
}
while my ajax request looks like this:
$("#select_age").click(function(){
$.ajax({
method: "POST",
url: "get_matches.php",
dataType: "json",
data: {
min_search: $( "#slider-range" ).slider( "values", 0 ),
max_search: $( "#slider-range" ).slider( "values", 1 )
},
success: function(data){
var myvar = jQuery.parseJSON(data);
window.alert(myvar)
}
});
});
A var_dump($result) should look like this:
array(2) {
[0]=>
array(6) {
["username"]=>
string(6) "giulia"
["birth"]=>
string(10) "05/10/1990"
["city"]=>
string(6) "Torino"
["gender"]=>
string(1) "F"
["os"]=>
string(7) "Windows"
["persontype"]=>
string(4) "ENFP"
}
[1]=>
array(6) {
["username"]=>
string(7) "taiga27"
["birth"]=>
string(10) "07/27/1998"
["city"]=>
string(6) "Torino"
["gender"]=>
string(1) "F"
["os"]=>
string(7) "Windows"
["persontype"]=>
string(4) "ISTP"
}
}
When I get to the var myvar = jQuery.parseJSON(data); I get an error "Unexpected token a in JSON at position 2"
What am I getting wrong? How do I initialize a correct JSON multidimensional array inside a foreach? And how do I to retrieve the data once in the ajax success function?
Upvotes: 0
Views: 278
Reputation: 13354
A few notes:
You do not need to increment $count
in order to append to an array. Simply exclude the index (see below).
You do not need to place your variables inside double quotes. Simply pass the variable without any quotation marks at all.
Your example code has some extra closing brackets, maybe you have other code before/after what you shared, but if not, you certainly don't need so many brackets.
You should not use var_dump()
to return the data, simply echo()
the JSON-encoded results string (as you have in your example).
$result = array();
foreach($matches_lines as $lines){
$match_user = $lines["signup_username"];
$match_birth = $lines["signup_birth"];
$match_city = $lines["signup_city"];
$match_gender = $lines["signup_gender"];
$match_os = $lines["signup_os"];
$match_persontype = $lines["signup_persontype"];
if( 1 == 1 ){ // replace with "some check on the variables"
$result[] = array('username' => $match_user, 'birth'=> $match_birth, 'city' => $match_city, 'gender' => $match_gender, 'os' => $match_os, 'persontype' => $match_persontype);
}
}
echo json_encode($result);
Upvotes: 0