用于输出数组,而不是使用json_encode,使用what。(如何输出(echo)数组不使用json_encode?)我使用codeigniter。
CI_Controller:
function auto_complete(){
$hotel_search = $this->input->post('search_hotel');
echo json_encode($this->model_tour->auto_complete($hotel_search));
// if use of json_encode output is '[{"name":"salal"},{"name":"salaso"},{"name":"salasi"},{"name":"salsh"}]' if don want use of json_encode output is "Array"
}
CI_model:
function auto_complete($hotel_search)
{
$query_hotel_search = $this->db->order_by("id", "desc")->like('name', $hotel_search)->get('hotel_submits');
if($query_hotel_search->num_rows()==0){
return '0';
}else{
$data = array();
foreach ($query_hotel_search->result() as $row)
{
$data[] = array('name' => $row->name);
}
return $data;
}
}
如果您只想查看数组,print_r($array)
或var_dump($array)
都可以
我不确定这是否是你正在寻找的,但它确实有助于显示数组的结构/JSON:
echo "<pre>";
print_r($array);
echo "</pre>";
它将显示拆分的$数组,并保留选项卡,以便您可以看到它是如何嵌套的。
如果要查看数组的内容,请使用print_r
或vardump
如果你想对这些信息做一些有用的事情,你必须循环遍历数组
foreach($this->model_tour->auto_complete($hotel_search) as $key => $value){
//do something
}
foreach($array as $key => $value){Echo $key。' = '。美元的价值。"' n";} 之前将以字符串的形式给出数组。
也可以使用print_r()
<>以前print_r(数组)美元;之前或var_dump ()
<>以前var_dump(数组)美元;
您有几个选项可供选择:
-
json_encode
(你自己提到的) -
print_r
或var_dump
(timw4mail提到这个) -
implode
(然而,这对嵌套数组不起作用,它只会显示键) -
array_map
(使用自己的函数格式化单个数组元素)和implode
(组合结果)的组合 - 编写自己的递归函数,将数组扁平化为字符串
如果使用jQuery,任何.ajax()、.get()或.post()函数都会尝试猜测从HTTP请求返回的数据类型。将控制器的内容类型设置为JSON:
$hotel_search = $this->input->post('search_hotel');
$this->output
->set_content_type('application/json')
->set_output( json_encode($this->model_tour->auto_complete($hotel_search)) );