how is output(echo) array without use of json_encode?(codeigniter)

时光怂恿深爱的人放手 提交于 2021-02-05 11:50:27

问题


for output array Instead of using json_encode, use of what.(how is output(echo) array without use of json_encode?) i use of 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;          
        }
}

回答1:


If you just want to view the array, print_r($array) or var_dump($array) will work




回答2:


I'm not sure if this is what you are looking for, but it really helps show the structure of the array/JSON:

echo "<pre>";
print_r($array);
echo "</pre>";

It will show the $array broken out and will keep the tabbing so you can see how it's nested.




回答3:


If you want to view the contents of the array, use print_r or vardump

If you want to do something useful with the information, you're going to have to loop through the array

foreach($this->model_tour->auto_complete($hotel_search) as $key => $value){
    //do something
}



回答4:


foreach($array as $key => $value)
{
    echo $key . ' = ' . $value . "\n";
}

That will give you the array as string.

You can also use print_r()

print_r($array);

or var_dump()

var_dump($array);



回答5:


You have a few options at your disposal:

  • json_encode (which you mention yourself)
  • print_r or var_dump (timw4mail mentions this)
  • implode (however, this won't work for nested arrays, and it will only display the keys)
  • a combination of array_map (to format individual array elements using your own function) and implode (to combine the results)
  • write your own recursive function that flattens an array into a string



回答6:


If you're using jQuery, any .ajax(), .get(), or .post() function will try to guess the data type being returned from the HTTP request. Set the content type of your controller to 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)) ); 


来源:https://stackoverflow.com/questions/6748938/how-is-outputecho-array-without-use-of-json-encodecodeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!