如果使用php(laravel)未定义数组元素,则将null插入数据库

时间:2014-05-08 19:28:43

标签: php arrays laravel insert laravel-4

我正在尝试将数组插入表中,但未定义数组的某些元素。 我想插入null,其中元素未定义。 数组如下:

[0]=>Array
 (
   [0] => Array
    (
        [Id] => 120
        [Title] => PHP
        [Year] => 2011
        [Version] =>5.5
    )

   [1] => Array
    (
        [Id] => 121
        [Title] => Javascript
        [Year] => 2010
        [Version] =>7
    )

 )
 [1]=>Array
 (
   [0] => Array
    (
        [Id] => 1
        [Title] => Html
        [Author] => peter
    )

   [1] => Array
    (
        [Id] => 1
        [Title] => Asp
        [Author] => john
    )

 )
  [2]=>Array
 (
   [0] => Array
    (
        [Id] => 1
        [Title] => Html
        [Year] => 2011
        [Page] =>40
    )

   [1] => Array
    (
        [Id] => 1
        [Title] => Asp
        [Year] => 2010
        [Page] =>220
    )

 )

表有6个字段ID,标题,年份,作者,版本和页面。

 $this ->table->create(array(
    'id'       => $data['Id'] ,
   'title'     => $data['Title'] ,
   'year'      => $data['Year'] ,
   'author'    => $data['Author'],
   'version'   => $data['Version'] ,
   'page'      => $data['Page'] ,
   ))

如果未定义变量,如何向表中插入null。例如喜欢 undefined($ data ['Version'])? null:$ data ['Version'] !!!!!!一个PHP功能或任何可能的解决方案? 感谢

1 个答案:

答案 0 :(得分:0)

你可能会:

foreach($data as $row)
{
    $info = array(
       'id'       => $this->getData($row, 'Id'),
       'title'     => $this->getData($row, 'Title'),
       'year'      => $this->getData($row, 'Year'),
       'author'    => $this->getData($row, 'Author'),
       'version'   => $this->getData($row, 'Version'),
       'page'      => $this->getData($row, 'Page'),
    );

    $this->table->create(array_filter($info));
}

public function getData($data, $key)
{
    return isset($data[key]) ? $data[key] : null;
}
相关问题