我正在尝试使用循环创建JSON数组,我在数据库中存储语言名称并从查询中检索,之后我需要将其转换为此格式
$arrayName = array('lang-1' => null , 'lang-2' => null, ..... ,'lang-n' => null );
我怎样才能实现
PHP代码就像这样
include_once "inc/init.php";
header('Content-Type: application/json');
$arrayName = array();
$query = $db->query("SELECT * FROM `medium`");
while ($data = mysqli_fetch_assoc($query)) {
array_push($arrayName, $data['medium']);
}
echo json_encode($arrayName);
我加入这种格式
[
"Kannada",
"Telugu",
"Tamil",
"Urdu",
"Spanish",
"Arabian"
]
我试图推动价值,但我没有采用这种格式,请帮助我
谢谢
答案 0 :(得分:2)
根据您的评论,我认为$data['language']
代表您的语言名称。然后,您可以通过以下代码实现目标:
include_once "inc/init.php";
header('Content-Type: application/json');
$arrayName = array();
$query = $db->query("SELECT * FROM `medium`");
while ($data = mysqli_fetch_assoc($query)) {
$arrayName[$data['language']] = null; // $array[$key] = $value
}
echo json_encode($arrayName);
答案 1 :(得分:1)
使用array_push,您将获得相同的结果
include_once "inc/init.php";
header('Content-Type: application/json');
$arrayName = array();
$query = $conn->query("SELECT * FROM `medium`");
while ($data = mysqli_fetch_assoc($query)) {
array_push($arrayName,$data['language ']);
}
$arrayName=array_fill_keys($arrayName, 'null');
echo json_encode($arrayName);