duanjiu1950
2017-03-18 18:18
浏览 92

使用PHP将另一个数据添加到json数组

I'm trying to create a JSON array with loop, I stored languages name in database and retrieving from query, after that I need to convert it into this format

$arrayName = array('lang-1' => null , 'lang-2' => null, ..... ,'lang-n' => null );

how can I achieve that

PHP code is like this

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);

im getting in this format

[
 "Kannada",
 "Telugu",
 "Tamil",
 "Urdu",
 "Spanish",
 "Arabian"
]

im trying pushing value but im not getting in that format, please help me

Thank you

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用循环创建一个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(); \  n $ query = $ db-> query(“SELECT * FROM`media`”); 
while($ data = mysqli_fetch_assoc($ query)){
array_push($ arrayName,$ data ['medium']); \  n} 
echo json_encode($ arrayName); 
   
 
 

我得到这种格式

  [
“  Kannada“,
”“泰卢固语”,
“泰米尔语”,
“乌尔都语”,
“西班牙语”,
“阿拉伯语”
] 
   
 
 < 我试图推动价值,但我没有采用这种格式,请帮助我 
 
 

谢谢

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douzhuo2002 2017-03-18 18:36
    已采纳

    Based on your comments I'm asuming that $data['language'] represents a name of your language. Then you can achieve your goal by the following code:

    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);
    
    已采纳该答案
    打赏 评论
  • dongzhang6021 2017-03-18 18:50

    using array_push you will get the same result

    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);
    
    打赏 评论

相关推荐 更多相似问题