2012-08-17 50 views
0

我似乎与JSON解码被卡住了,我不知道如何JSON对象进行解码或者也许我做的事情很不对劲,IAM这样做的:无法到JSON解码

$error_fields_structure['product_id'] = $this->input->post('product_id'); 
$error_fields_structure['main_product_quantity'] = $this->input->post('quantity'); 
$error_fields_structure = json_encode($error_fields_structure); 

我$ error_fields_structure传递给我的看法在我的Java脚本我做的:

<?php print_r(json_decode($error_fields_structure)); ?>; 

我得到的萤火错误,下面的输出

stdClass Object 
(
[product_id] => 62 
[product_quantity] => 65 
); 

,但如果我这样做

<?php print_r(json_decode($error_fields_structure['product_id'])); ?>; 

它给了我一个空字符串和错误 我怎样从JSON对象$ error_fields_structure

+0

什么JavaScript有什么关系呢?如果是的话,你的萤火虫错误是什么? – 2012-08-17 11:09:16

+0

不能使用类型为stdClass的对象作为数组 – 2012-08-17 11:18:46

+0

也我想解码JavaScript中的json,这是可能的,如文档中给出的 – 2012-08-17 11:19:28

回答

3

只能解码一个有效的JSON字符串特别PRODUCT_ID和product_quantity。

<?php print_r(json_decode($error_fields_structure['product_id'])); ?>; 

不正确,因为$ error_fields_structure ['product_id']不是json字符串。

试试这个:

<?php 
$errorFieldsArr = json_decode($error_fields_structure,true); //convert json string to array 
var_dump($errorFieldsArr['product_id']); // get element from array 
?> 

<?php 
$errorFieldsArr = json_decode($error_fields_structure); //convert json string to stdobject 
var_dump($errorFieldsArr->product_id); // get element from object 
?> 
+0

工程完美,赞! – 2012-08-17 11:16:58

+0

Pathak 我该如何分配json数组(转换)为java脚本数组? var demo = new array(); demo = <?php(json_decode($ error_structure,true)); ?> 我怎么能这样做?\ – 2012-08-17 11:23:24

+0

你应该只是在你的javascript代码而不是你的php代码中解码json,你可以使用jquery使它更容易 – 2012-08-17 13:10:45