2013-10-01 39 views
0

好傢伙,我有這個字符串JSON和我與函數Php對其進行解碼json_decode($var,true)最後一個參數數組

[{"id":"4","name":"Elis"},{"id":"5","name":"Eilbert"}] 

一樣的結果我得到這個數組

Array([0] => Array ([id] => 4 [name] => Elis) 
     [1] => Array ([id] => 5 [name] => Eilbert))1 

這是什麼最後的數字「 1「在數組的末尾?爲什麼那裏?我不想要它,我該如何刪除它?

在js上,我傳遞一個用JSON.stringify()轉換的數組,結果就像第一個json代碼。

$user = json_decode($this->input->post('to'),true); 
       $conv_user_id = array(); 
       foreach ($user as $po) { 
        $conv_user_id[] = $po['id']; 
        $conv_user_id[] = $id_user; 

       } 

       echo print_r($user); 

@explosion菲爾向我指出,我的JSON字符串是包裹着[]我通過只是在JS陣列轉換它witj JSON.stringify(),至極是誤差?

+0

你的意思'json_decode'? –

+0

是的,解碼抱歉 – fabrizio

+1

顯示您的實際代碼,請 –

回答

4

你濫用print_r()

echo print_r($user); 

如果你想捕捉的print_r()的輸出,使用返回參數。當此參數設置爲TRUE時,print_r()將返回信息而不是打印它。

當返回參數爲TRUE時,此函數將返回一個字符串。否則,返回值爲TRUE

...當你把布爾值TRUE轉換爲字符串時,你會得到1

+0

準確地說,我不知道,但我不是這一個地雷問題,但你有正確的答案我的問題。 – fabrizio

1

Learn more about json_decode - 解碼JSON字符串。

例常見的錯誤使用json_decode()

<?php 

// the following strings are valid JavaScript but not valid JSON 

// the name and value must be enclosed in double quotes 
// single quotes are not valid 
$bad_json = "{ 'bar': 'baz' }"; 
json_decode($bad_json); // null 

// the name must be enclosed in double quotes 
$bad_json = '{ bar: "baz" }'; 
json_decode($bad_json); // null 

// trailing commas are not allowed 
$bad_json = '{ bar: "baz", }'; 
json_decode($bad_json); // null 

?> 

Ref:

相關問題