PHP通过键写入新的数组值或创建新行


PHP Write new array value by key or create new line

我想用php读取单个数组值,并将它们保存为一个键。如果该键不存在,则应创建一个新条目。

这是我的语言文件读写:

$LNG['name'] = array(
    1 => 'test',
    2 => 'test1',
    3 => 'test2',
    4 => 'test3',
    5 => 'test4',
);

以下是示例

<?php
$include("TECH.php");
$name = $LNG['name'][$_GET['id']];
?>
<html>
<head>
    <title>Editpage</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
    <table>
<tr>
    <td>Name</td><td><input name="name" type="text" value="{$name}"/></td>
</tr>    
</table>
    <p><input type="submit" name="submit" value="Save"></p>
</form>
</body>
</html>

并通过提交所选密钥的更改值

示例通过提交从密钥1到的更改值,密钥为1

$LNG['name'] = array(
    1 => 'i am edited',
    2 => 'test1',
    3 => 'test2',
    4 => 'test3',
    5 => 'test4',
);

为了保存,我测试了这个

$file = 'TECH.php';
// The new person to add to the file
$saveedit = $LNG['tech'][$_GET['id']] = $_POST['name_ger'];
// Write the contents to the file, 
file_put_contents($file, $saveedit, FILE_APPEND | LOCK_EX);

这添加了编辑名称什么都没有他添加了一个新的条目

$LNG['name'] = array(
    1 => 'test',
    2 => 'test1',
    3 => 'test2',
    4 => 'test3',
    5 => 'test4',
);editvalue

所以您想将数据存储在一个文件中,在一个数组中,PHP可以通过简单地包含该文件来"读取"数据?

然后,要修改该数据,您也可以简单地包含该文件,以便变量/数据结构$LNG['name']出现在处理提交表单的脚本中。

要修改值,只需覆盖它们:

$LNG['name'][$idfromform] = $valuefromform;

不需要检查密钥是否存在,如果不存在,PHP将自动创建它。

然后,要将修改后的数据结构写回文件,只需使用var_exportfile_put_contents

不过,您可能需要考虑以某种方式限制可以在数组中创建哪些键。并保护该表单不被您网站的任何用户使用,否则您可能会出现不必要的副作用,甚至可能造成安全漏洞。但这在很大程度上取决于您以后将如何处理数据结构。