<?php
class User {
public $id;
public $counter;
public $removed;
}
$dB = json_decode(file_get_contents('dataBase.json'), true);
$dataBase = &$dB['noob'];
$userInDB = null;
$user = array('id' => (int)$_GET['id'], 'counter' => (int)$_GET['counter'], 'removed' => (bool)$_GET['removed']);
foreach ($dataBase as $usr) {
if ($usr['id'] == $user['id']) {
$userInDB = &$usr;
break;
}
}
if ($userInDB) {
$userInDB['counter'] = $userInDB['counter'] + $user['counter'];
$userInDB['removed'] = $user['removed'];
print_r($userInDB);
} else {
$dataBase[] = $user;
print_r($dataBase);
}
if(isset($_GET['id'])) {
$json = json_encode($user);
$updateddB = json_encode($dB);
file_put_contents('dataBase.json', $updateddB);
}
?>
除我尝试在数组中编辑值的部分外,所有内容均有效。 $ userInDB已更改,但是即使在我确定已引用的情况下,它在$ dB内引用的部分也未更改。有人请帮忙,我的头已经打结了。
答案 0 :(得分:0)
您有以下循环:
foreach ($dataBase as $usr) {
if ($usr['id'] == $user['id']) {
$userInDB = &$usr;
break;
}
}
$userInDB
是对$usr
的引用,但是$usr
只是由foreach
循环创建的,并未引用它正在循环的原始数组。举例来说,您有一个非常简单的案例:
foreach ($foo as $var) {
$var++;
}
这根本不影响$foo
。
您需要做的是直接引用$dataBase
变量:
foreach ($dataBase as $key => $usr) {
if ($usr['id'] == $user['id']) {
$userInDB = &$dataBase[$key];
break;
}
}