简体   繁体   English

将键值对从数据库添加到php关联数组

[英]Add key value pair to php associative array from Database

DB is set up as such: 数据库设置如下:

在此处输入图片说明

include 'php/DbConnect.php';
$sql = $mysqli->query(
 "SELECT t.*, v.* 
 FROM task t 
 INNER JOIN vocabtask vt ON (t.id = vt.taskid)
 INNER JOIN vocab v ON (v.id = vt.vocabid)
 WHERE vt.taskid = 1");
$wordsArray = array();  


while ($row = $sql->fetch_assoc()) {

   // echo "<br> " . $row['taskname'] . ": ".  $row['chinese'] . " : " . $row['english'];
    $wordsArray['chinese']['english'] = $row['chinese'];
    echo $wordsArray['chinese']['english'];
}
mysqli_close($mysqli);  

Output: Ni Ta Wo 输出: Ni Ta Wo

Desired output: Ni: You Ta: Him Wo: I 期望的输出: Ni: You Ta: Him Wo: I

I want the Chinese word (key) and associated English translation (value) loaded into wordsArray, but don't know the correct syntax to load and to access. 我想将中文单词(关键字)和相关的英语翻译(值)加载到wordsArray中,但是不知道加载和访问的正确语法。

Thanks 谢谢

Perhaps you want this? 也许您想要这个? It maps one direction, Chinese to English, but there's not a really great way to do bidirection mapping as far as I know. 它将一个方向映射为中文到英语,但据我所知,并没有一种很好的双向映射方法。 (Typically I use two mappings to do that.) edit: It seems this is the direction you want, based on your edit. (通常,我使用两个映射来做到这一点。)编辑:根据您的编辑,这似乎是您想要的方向。

$wordsArray = array();
while ($row = $sql->fetch_assoc()) {
    $wordsArray[$row['chinese']] = $row['english'];
}
mysqli_close($mysqli);  
var_dump($wordArray);
$json = array();
foreach (...) {
    $json[$row['chinese']] = $row['english']
}

$return_result = json_encode($json);

echo $return_result;

you may grab that return value with jQuery and parse it as jSON with jQuery.parseJSON() with/without ajax. 您可以使用jQuery获取该返回值,并使用带有/不带有ajax的jQuery.parseJSON()其解析为jSON。

update, if you don't want parse the data with ajax just add the result to the page within a script tag like 更新,如果您不想使用ajax解析数据,只需将结果添加到script标签中的页面中,例如

<script type="text/javascript">
(function($){
    var data = '<?php echo $return_result; ?>';
    var json = $.parseJSON(data);
    console.log(json);
})(jQuery);
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM