Php,键值增加1的问题

Php,键值增加1的问题,php,foreach,Php,Foreach,我花了两天的时间来解决这个问题。我试图创建一个投票脚本,它读取.txt文件并修改其中的值。我对我试图在个人投票中增加+1的每一部分都有问题。1-5为个人id,|后的数字为票数。第一个输出是: Array ( [0] => 1|2 [1] => 2|6 [2] => 3|8 [3] => 4|3 [4] => 5|10 我希望它在最后一个数字中加上+1。但若我尝试使用increment,我会得到一个错误:“PHP致命错误:不能递增/递减重载对象,也不能在 我

我花了两天的时间来解决这个问题。我试图创建一个投票脚本,它读取.txt文件并修改其中的值。我对我试图在个人投票中增加+1的每一部分都有问题。1-5为个人id,|后的数字为票数。第一个输出是:

Array
(
[0] => 1|2

[1] => 2|6

[2] => 3|8

[3] => 4|3

[4] => 5|10
我希望它在最后一个数字中加上+1。但若我尝试使用increment,我会得到一个错误:“PHP致命错误:不能递增/递减重载对象,也不能在

我还在学习PHP,这对我来说很奇怪,因为只要给“$id[2]=8”实际上就修改了这个值。为什么不能使用++呢?这是怎么回事

Array
(
[0] => 1|2

[1] => 2|8

[2] => 3|8

[3] => 4|3

[4] => 5|10
)

改用json。这会让你的生活更轻松

Json是一个文本字符串,可以在数组中解码。
索引数组或关联数组。在我看来,在这种情况下,联想是首选

$votes = ["1" => 2, "2" => 6, "3" => 8, "4" => 3, "5" => 10];
// Above is an associative array with the same data as your example. 
// The key is the id and the value is the votes.
// To read it from the file use:
// $votes = json_decode(file_get_contents("file.txt"));

$inputVote = 2; // someone voted on person 2.

if(!isset($votes[$inputVote])) $votes[$inputVote] = 0; // if someone voted on a person not already in the array, add the person to the array. 

$votes[$inputVote]++; // increments the votes on person 2.

file_put_contents("file.txt", json_encode($votes));

您的意思是要在字符串的这一部分增加值
1 | 2
首先需要将其分解,然后增加拆分后的整数,然后再次内爆,然后再次写入文件,您知道吗?为什么不首先使用person id作为数组键,并且只存储计数器作为值?您应该使用标准化的数据格式,如csv或json,并使用适当的工具来读写、修改和保存数据。在您的示例中,您可能使用csv和
作为分隔符,并使用
fgetcsv()
读取和解析数据。数组([ID\u OF_PERSON]=>2)以上述格式创建数组。我的示例中有一个拼写错误,duh。我使用的是$id[2]++来递增,例如2/6到2/7。但是只有$id[2]=(这里的任何数字)似乎有效,这不起作用。@bonekuukkeli是的,它会有效,但不会像json字符串那样通用。因为您使用的是索引数组,所以很难跟踪内容$在您的情况下,id[2]是第三个人。在我的例子中,$vots[3]是person 3。我不需要在字符串I just++中使用
|
进行任何字符串处理;一切都结束了。
$votes = ["1" => 2, "2" => 6, "3" => 8, "4" => 3, "5" => 10];
// Above is an associative array with the same data as your example. 
// The key is the id and the value is the votes.
// To read it from the file use:
// $votes = json_decode(file_get_contents("file.txt"));

$inputVote = 2; // someone voted on person 2.

if(!isset($votes[$inputVote])) $votes[$inputVote] = 0; // if someone voted on a person not already in the array, add the person to the array. 

$votes[$inputVote]++; // increments the votes on person 2.

file_put_contents("file.txt", json_encode($votes));