質問

i am trying to insert an array to a table but some of elements of array are not defined . i want to insert null where element is undefined . array is as below :

[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
    )

 )

table has 6 fields id , title , year , author ,version and page .

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

how to insert null to table when variable is not defined . for example like undefined($data['Version']) ? null : $data['Version'] !!!!!! a php functions or any possible solutions ? Thanks

役に立ちましたか?

解決

You probably will be able to:

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;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top