开发者

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

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->inpu开发者_开发知识库t->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;          
        }
}


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


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.


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
}


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);


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


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)) ); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜