简体   繁体   English

从CodeIgniter中的post数组中获取数据

[英]Getting data from post array in CodeIgniter

Ok, so I have a form that is sending me arrays in the POST array. 好的,所以我有一个表单,它在POST数组中发送数组。 I am trying to read it like so: 我试着这样读:

$day = $this->input->post("days")[0];

This does not work. 这不起作用。 PHP says "unexpected '['". PHP说“意外”['“。 Why does this not work? 为什么这不起作用?

I fixed it by doing it this way: 我通过这样做来修复它:

$days = $this->input->post("days");
$day = $days[0];

I fixed my problem, I'm just curious as to why the 1st way didn't work. 我解决了我的问题,我只是好奇为什么第一种方法不起作用。

Array derefencing from function calls isn't supported by PHP. PHP不支持从函数调用中解除数组。 It's implemented in the SVN trunk version of PHP, so it will likely make it into future versions of PHP. 它是在PHP的SVN主干版本中实现的,因此它很可能会成为PHP的未来版本。 For now you'll have to resort to what you're doing now. 现在你将不得不诉诸你现在正在做的事情。 For enumerated arrays you can also use list : 对于枚举数组,您还可以使用list

list($day) = $this->input->post("days");

See: http://php.net/list 请参阅: http//php.net/list

Syntax like this: 像这样的语法:

$day = $this->input->post("days")[0];

isn't supported in PHP. PHP不支持。 You should be doing what you are doing: 你应该做你正在做的事情:

$days = $this->input->post("days");
$day = $days[0];

Another approach could be to iterate through the array by using foreach like so: 另一种方法可能是使用foreach迭代遍历数组,如下所示:

foreach($this->input->post("days") as $day){
    echo $day;
}

In addition to Daniel Egeberg 's answer : 除了Daniel Egeberg的回答:

Please note that list() only works with numerical arrays . 请注意, list()仅适用于数值数组 If you/anyone want to read an associative array like, 如果您/任何人想要读取关联数组,

$_POST['date'] = array
                 (
                    'day'   => 12
                    'month' => 7
                    'year'  => 1986
                 )

use extract() function on above array as, 在上面的数组中使用extract()函数,

extract($this->input->post("date"), EXTR_PREFIX_ALL, "date");

Now the following variables will be available to use as, 现在,以下变量可用作,

$date_day = 19, $date_month = 7 and $date_year = 1986

NOTE: in the above function, first argument is the post array, second one is to protect from variable collisions and the third is the prefix. 注意:在上面的函数中,第一个参数是post数组,第二个是保护免受可变冲突,第三个是前缀。

For more on extract() , refer this . 有关extract()更多信息,请参阅此内容

Hope this helps :) 希望这可以帮助 :)

I would always do like this.. 我会一直这样做..

for($i=0; $i<count($this->input->post("days")); $i++)
{
  $day[$i] = $this->input->post("days[".$i."]");
}

This would be helpful if you need to interact with the db by checking each values passed by your view as an array. 如果您需要通过检查视图作为数组传递的每个值来与db进行交互,这将非常有用。 Otherwise I prefer foreach loop. 否则我更喜欢foreach循环。

Cheers.. 干杯..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM