Codeigniter - post中的json对象数组


Codeigniter - array of json objects in post

在火虫中,我查看我的jquery后请求参数,它是这样的

adults            1
applicants[]    [object Object]
attendees   1
children    0

在这篇文章请求中,名为 applicant 的数组包含 json 对象,我希望 ti 迭代并在我的代码点火器控制器中提取值。json 字符串可能如下所示

({attendees:"2", 
  adults:"2", 
  children:"0", 
  grptype:"2", 
  'applicants[]':[{firstname:"John", lastname:"Doe", age:"33", allergies:"true", diabetic:"true",    lactose:"false", note:"nuts"}, {firstname:"Jane", lastname:"Doe", age:"34", allergies:"true", diabetic:"false", lactose:"false", note:"pollen"}]
})

查看上面的申请人[],请参阅我有两个人的信息作为json对象。我不确定如何访问控制器中的数据。看到这里

$applicants = $this->input->post('applicants');
$this->output->append_output("<br/>Here: " . $applicants[0].firstname );

我在想$applicants[0] woild 引用 json 对象,我可以根据需要提取值。不确定我做错了。谢谢大家。

编辑所以我调整了我的json,看起来像这样

adults  2
applicants[]    {firstname:"John", lastname:"Doe", age:"23", allergies:"true", diabetic:"true", lactose:"false", note:"nuts"}
applicants[]    {firstname:"Jane", lastname:"Doe", age:"23", allergies:"false", diabetic:"false", lactose:"false", note:""}
attendees   2
children    0

现在我仍然收到一个错误说

**Message: json_decode() expects parameter 1 to be string, array given**

有什么想法吗?

编辑 2

好的mu数据现在像这样

adults  1
applicants[]    {"firstname": "John", "lastname": "Doe", "age": "34", "allergies": "true", "diabetic": "true", "lactose": "false", "note": "nuts"}
attendees   1
children    0

在控制器 ID 中执行此操作

$applications = $this->input->post('applicants');
foreach ( $applications as $item)
{
  $item = json_decode($item, true);  
  $this->output->append_output(print_r($item));
}

这是该逻辑的结果

Array
(
    [firstname] => John
    [lastname] => Doe
    [age] => 34
    [allergies] => true
    [diabetic] => true
    [lactose] => false
    [note] => nuts
)

不确定我做错了什么,无论我做什么来访问日期器,我都会收到一个错误,大意是我无法像那样访问它。如何提取值?

您必须在服务器上

使用
$applications = json_decode($this->input->post('applicants'), true);

因此,它将成为关联数组,您可以像array一样使用它,如果没有第二个参数(true(,json_decode json将被转换为对象。在你解码它之前,它只是一个string(json/java script object notation字符串(。

更新:由于它已经是一个对象数组,那么你不需要使用json_decode,只需像这样在view中循环数组

foreach($applicants as $item)
{
     echo $item->firstname . '<br />';
     echo $item->lastname . '<br />';
     // ...
}

根据编辑 2,它应该作为数组访问

echo $item['firstname'] . '<br />'

请尝试此操作

$applicants = $this->input->post('applicants');
$json_output = json_decode($applicants );
foreach ( $json_output as $person)
{
  $this->output->append_output("<br/>Here: " . $person->firstname );
}

$json_output = json_decode($applicants,TRUE );
echo $json_output[0][firstname] ;