[英]I am having issues with Array to JSON structure in PHP to be used in Javascript
I always struggle with Array to JSON formatting. 我一直在努力将Array转换为JSON格式。 I am using a selectbox plugin from TexoTela.
我正在使用TexoTela的selectbox插件。 The plugin requires a json structure as:
该插件需要一个json结构,如下所示:
{
"ajax1": "AJAX option 1",
"ajax2": "AJAX option 2",
"ajax3": "AJAX option 3"
}
My php code: 我的PHP代码:
function get_selectfield_list($col, $table)
{
$location_list = array();
//create an sql string and set it to the $sql variable
$sql = "SELECT id, $col FROM $table";
//form the sql query and set it to the $query variable
$query = $this->db->query($sql);
//loop through the result_array and set the results to the $location_list array
foreach ($query->result_array() as $row)
{
$value = $row['id']; //set the database table id to to $value variable
$text = $row[$col]; //set the the $string value to the $text variable
$location_list = array($value => $text); //form the $location_list array with the the $value and $text values
}
echo json_encode($location_list); //convert the $location_list array into a json object and return it.
}
My PHP code returns {"4":"chickenpen 4"}
我的PHP代码返回
{"4":"chickenpen 4"}
Instead of {"4":"chickenpen 4","5":"chickenpen 5", etc....}
代替
{"4":"chickenpen 4","5":"chickenpen 5", etc....}
I think that is due to the code: $location_list = array($value => $text); 我认为这是由于代码:$ location_list = array($ value => $ text); Every time the foreach loops it creates a new array.
每次foreach循环时,它都会创建一个新数组。 How do I format the array to output all the results in the foreach instead of the last result?
我如何格式化数组以在foreach中输出所有结果,而不是最后一个结果?
-Rich -丰富
$location_list[$value] = $text;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.