我想将数组从视图保存到数据库 但我无法从视图中获取数组。
在视图页面中
<?php
$nilai = array(
array(1,2,3,4),
array(a,b,c,d)
);
<a href="<?= BASEURL; ?>/penerima/tambah?nilai=$nilai" class="btn btn-l btn-info">simpan</a>
在控制器页面中
<?php
class Penerima extends Controller
{
public function index()
{
$data['penerima'] = $this->model('Penerima_model')->getAll();
$this->view('templates/header');
$this->view('penerima/index', $data);
$this->view('templates/footer');
}
public function tambah() and I'm using MVC concept
{
$nilai = $_GET['nilai'];
$this->model('Penerima_model')->tambahData($nilai);
}
}
我有二维数组。
如何解决此问题?
我找到了解决方案。这是对我有用的。我使用
json_encode()
解决方案是转义字符,所以我不得不将上面的行替换为
htmlspecialchars(json_encode(array))
溶液:
$nilai = array(
array(1,2,3,4),
array('a','b','c','d')
);
<a href="http://localhost/code/tambah?nilai=<?= htmlspecialchars(json_encode($nilai)); ?>" class="btn btn-l btn-info">simpan</a>
在控制器中,我必须使用以下行从 JSON 获取我的数组
function tambah(){
$dataJson = $this->input->get('nilai');
$dataArray = json_decode(htmlspecialchars_decode($dataJson), true);
print_r($dataArray);
}
最佳解决方案
最好的方法是使用会话
$this->session->set_userdata('nilai',$nilai);
<a href="http://localhost/code/tambah" class="btn btn-l btn-info">simpan</a>
现在,进入控制器
function tambah(){
$array = $this->session->userdata('nilai');
}
注意:在控制器中加载会话库或自动加载
查看参考 将数组作为 url 参数传递 如果您正在使用codeigniter framework
那么要从 URL 获取值,请尝试使用
$nilai = $this->input->get('nilai');
You can't send array in get request as it is. So you can change your code as shown below
in view page
<?php
$nilai = array(
array(1,2,3,4),
array(a,b,c,d)
);
$nilai = json_encode($nilai);
<a href="<?= BASEURL; ?>/penerima/tambah?nilai=$nilai" class="btn btn-l btn-info">simpan</a>
in controller page
<?php
class Penerima extends Controller`
{
public function index()
{
$data['penerima'] = $this->model('Penerima_model')->getAll();
$this->view('templates/header');
$this->view('penerima/index', $data);
$this->view('templates/footer');
}
public function tambah()
{
$nilai = $_GET['nilai'];
$nilai = json_decode($nilai);
$this->model('Penerima_model')->tambahData($nilai);
}
}
您可以json_encode
array
并使用urlencode
传递它。
在您看来:
<?php
$nilai = array(
array(1,2,3,4),
array(a,b,c,d)
);
// encode to json string and encode to valid url
$nilai_urlencoded = urlencode(json_encode($nilai));
?>
<a href="<?= BASEURL; ?>/penerima/tambah?nilai=<?=$nilai_urlencoded; ?>" class="btn btn-l btn-info">simpan</a>
在控制器中,解码json
字符串
<?php
class Penerima extends Controller
{
public function index()
{
$data['penerima'] = $this->model('Penerima_model')->getAll();
$this->view('templates/header');
$this->view('penerima/index', $data);
$this->view('templates/footer');
}
public function tambah()
{
// Decode the url first and then convert the json_string to array
$nilai = json_decode(urldecode($_GET['nilai'])));
$this->model('Penerima_model')->tambahData($nilai);
}
}