There is a sample of unique values ​​from the database in 3 columns

function getLocation($link){ mysqli_set_charset($link, "utf8"); $select = 'SELECT DISTINCT country FROM lost_animal'; $query = mysqli_query($link, $select) or die(mysqli_error($link)); $num = mysqli_num_rows($query); if($num != '0'){ for($i=0;$i<$num;$i++){ $arr[] = mysqli_fetch_array($query); } } $select = 'SELECT DISTINCT city FROM lost_animal'; $query = mysqli_query($link, $select) or die(mysqli_error($link)); $num = mysqli_num_rows($query); if($num != '0'){ for($i=0;$i<$num;$i++){ $arr[] = mysqli_fetch_array($query); } } $select = 'SELECT DISTINCT region FROM lost_animal'; $query = mysqli_query($link, $select) or die(mysqli_error($link)); $num = mysqli_num_rows($query); if($num != '0'){ for($i=0;$i<$num;$i++){ $arr[] = mysqli_fetch_array($query); } } return $arr; die(); } 

On the client side:

 data = {action:'get_location'}; $.post('inc/core.php', data, function(response){ console.log(response); obj = JSON.parse(response); $.each(obj, function(key, value){ console.log(value['city']); }); }); 

Why does the console display undefined?

 [{"0":"Latvia","country":"Latvia"},{"0":"Riga","city":"Riga"},{"0":"\u0420\u0438\u0436\u0441\u043a\u0438\u0439","region":"\u0420\u0438\u0436\u0441\u043a\u0438\u0439"},{"0":"riga","region":"riga"},{"0":"vot","region":"vot"},{"0":"Pildas iela","region":"Pildas iela"}] index.php:45 undefined index.php:45 Riga 4 index.php:45 undefined 

And is it the right decision to make 3 requests to display a unique value in 3 columns? How would you do?

  • 2
    In general one request collecting those that at you through union. But since you already asked, “how would you do it” ... I would make a database with a normal ( ru.wikipedia.org/wiki/… ) structure, i.e. Cities, Regions and Countries - Mike

1 answer 1

Because not all elements in your json array have the 'city' key. You dumped all three levels of classification into one array, so in addition to cities there are countries and regions, they do not have the element 'city'.

I probably would have made a tree json [{"country":"Latvia", "regions":[{"region":"riga", "cities":[{"city":"Riga"}]}]}] . or more simply: {"Latvia": {"riga": ["Riga",...]}}

 SELECT DISTINCT country, region, city FROM lost_animal ORDER BY country, region, city; 

Next, when sampling, we track changes in the country and region and add new elements at the changed level.