问题
I am trying to store this data in database but i am getting error. how to fix this?
I want simply store multidimensional array in a single column.
$data = array(
'2017' => array(
'6' => array(
'10' => array(
'count' => 76
),
),
),
);
$getdata = $this->view_count->setView($data);
Model
public function setView($data)
{
$setData = $this->db->where('short', 'honwl')->update('ci_links', $data['view_count']);
return $setData;
}
Error which i am getting A PHP Error was encountered
Severity: Notice
Message: Undefined index: view_count
Filename: models/View_count.php
Line Number: 14
Backtrace:
File: C:\wamp\www\blog\application\models\View_count.php Line: 14 Function: _error_handler
File: C:\wamp\www\blog\application\controllers\Dashbord.php Line: 52 Function: setView
File: C:\wamp\www\blog\index.php Line: 315 Function: require_once
A Database Error Occurred
You must use the "set" method to update an entry.
Filename: C:/wamp/www/blog/system/database/DB_query_builder.php
Line Number: 1864
回答1:
As message says, you don't have key $data['view_count']
but you have $data[2017][6][10]['count']
value. I asume those dates are changed dynamically so you need to get value of inner array by key count
.
If your array always has similar keys i.e. $data[year][month][day][count]
, you can use code (bit modified) from this answer to get that key value. Put in your model
private function getCount($arr, $search)
{
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach($iterator as $key => $value) {
if($search == $key && $value !== '') {
return $value;
}
}
return false;
}
Then in your first method use value filtered through this function:
public function setView($data)
{
$count = $this->getCount($data, 'count');
if ($count !== false) {
$setData = $this->db->where('short', 'honwl')->update('ci_links', $count);
return $setData;
}
return false;
}
回答2:
According to you example code, you can encode array data to JSON for saving to column, then get back by decode:
Controller:
$data = array(
'2017' => array(
'6' => array(
'10' => array(
'count' => 76
),
),
),
);
$getdata = $this->view_count->setView($data);
$data = $this->view_count->getView();
Model:
public function setView($data)
{
$data = json_encode($data);
$setData = $this->db->where('short', 'honwl')->update('ci_links', array('column_name'=>$data));
return $setData;
}
public function getView($data)
{
$row = $this->db->where('short', 'honwl')->get('ci_links')->row();
return json_decode($row->column_name, true);
}
The column_name
depends on your table's column name that save the array data.
来源:https://stackoverflow.com/questions/44475620/codeigniter-multidimensional-array-store-in-mysql-database-single-column