我想检索数组值。 这是我的数组值:
overlay.txt:
{"title":"sss","description":"sss","code":"sss"}
{"title":"trtr","description":"trtr","code":"tyrytr"}
{"title":"ret54","description":"56tr","code":"ty76"}
{"title":"rgfdg","description":"dfgdfg","code":"dfgdfg"}
{"title":"asfafdsf","description":"sdfsdf","code":"sdfsdfsdf"}
这是我的代码:但这不起作用。为什么? 如何从overlay.txt文件中检索值。 我没有得到所有的头衔价值。 我不知道如何从overlay.txt获取标题值 $ title显示为空。 我想在我的代码中更改以获得$ title值。
$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
$fd = fopen($file, "a"); // a for append, append text to file
fwrite($fd, $json);
fclose($fd);
$filecon = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays',$filecon);
//overlays page;
foreach($filecon as $files)
{
$title=$files['title'];
echo $title;
}
答案 0 :(得分:1)
您将编码您的数组转换为JSON,因此在某些时候您需要解码它再次进入PHP数组。由于文件中实际上有多个JSON对象,因此需要单独解码每个JSON对象。 假设它总是一行JSON对象每行,这样做:
$jsonObjects = file('overlay.txt', FILE_IGNORE_NEW_LINES);
foreach ($jsonObjects as $json) {
$array = json_decode($json, true);
echo $array['title'];
...
}
如果序列化JSON中存在换行符,则会很快破坏,例如:
{"title":"ret54","description":"foo
bar","code":"ty76"}
这种存储数据的方式不太可靠。
答案 1 :(得分:0)
使overlay.txt完全json格式:
[
{"title":"sss","description":"sss","code":"sss"},
{"title":"trtr","description":"trtr","code":"tyrytr"},
...
]
试试这个:
$raw = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays', array("filecon" => json_decode($raw)));
叠加页面:
<?php
foreach($filecon as $files) {
echo $files['title'];
}
?>
如果您想在视图文件中使用$filecon
,请执行
在$this->load->view()
的第二个参数中设置一个具有键“filecon”的数组
http://codeigniter.com/user_guide/general/views.html