0
我總是與陣列到JSON格式的鬥爭。我正在使用TexoTela的selectbox插件。該插件需要一個JSON結構爲:我在PHP中使用PHP中的數組到JSON結構的問題在JavaScript中使用
{
"ajax1": "AJAX option 1",
"ajax2": "AJAX option 2",
"ajax3": "AJAX option 3"
}
我的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.
}
我的PHP代碼返回{"4":"chickenpen 4"}
而不是{"4":"chickenpen 4","5":"chickenpen 5", etc....}
我認爲這是由於代碼:$ location_list = array($ value => $ text);每次foreach循環它創建一個新的數組。我如何格式化數組以輸出foreach中的所有結果而不是最後的結果?
富
這很簡單。我必須閱讀關於陣列。 – dottedquad 2011-04-07 17:31:36