-1

我想检索数组值。这是我的数组值:

覆盖.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;
    }
4

2 回答 2

1

您将数组编码为 JSON,因此在某些时候您需要再次将其解码为 PHP 数组。由于文件中实际上有多个 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"}

这种存储数据的方式不是很可靠。

于 2012-04-25T03:50:25.100 回答
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在视图文件中使用,请在第二个参数
中设置一个具有键“filecon”的数组。http://codeigniter.com/user_guide/general/views.html$this->load->view()

于 2012-04-25T04:05:27.487 回答