2016-11-05 67 views
-3

我可以知道如何从数据库中获取仅在json中的值数组而不是整个json对象吗?如何通过php从数据库中检索JSON的值?

<?php 
require_once('dbConnect.php'); 
$sql = "SELECT RestaurantName FROM Restaurant"; 
$result = mysqli_query($connection, $sql) or die("Error in Selecting " .  mysqli_error($connection)); 
$restaurantArray = array(); 
while($rows = mysqli_fetch_assoc($result)) { 
$restaurantArray[] = $rows; 
} 
echo json_encode($restaurantArray); 
mysqli_close($connection); 
?> 

例如,

["Afonso Cláudio", "Água Doce do Norte"] 

,而不是

[{"city":"Afonso Cláudio"},{"city":"Água Doce do Norte"}] 

回答

0

assoc这个数据库中获取数据时,会得到一个关联数组(当它转换成json时将成为一个json对象)。
你现在正在做的是将行(它是一个具有一个键值的关联数组)添加到结果数组中。如果你想只有想要这个城市,你可以很容易地从assoc数组中取数据。
更改

$restaurantArray[] = $rows; 

$resturantArray[] = $rows['city']; 

应该做的伎俩。

此外,如果你想重新格式化结果的数据,而不仅仅是推动城市的名字给它,一个array_map呼叫可用于:

$result = array_map(function($assocArr) { 
    return $assocArr['city']; // Or whatever you want the value to be. 
}, 
$resturantArray); 

echo json_encode($result); 
0

你怎么样改变这一行:

$restaurantArray[] = $rows; 

有了:

$restaurantArray[] = $rows['city']; // (or 'RestaurantName')