dongtuwu8548 2018-07-10 23:17
浏览 48
已采纳

PHP变量不作为参考

<?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);
}
?>

Everything works except the part where I attempt to edit a value within an array. $userInDB is changed, but the section that it refers to within $dB isn't, even though I'm pretty sure I referred to it. Someone please help, I've had my head in knots.

  • 写回答

1条回答 默认 最新

  • dongzang5815 2018-07-10 23:47
    关注

    You have the following loop:

    foreach ($dataBase as $usr) {
        if ($usr['id'] == $user['id']) {
            $userInDB = &$usr;
            break;
        }
    }
    

    The $userInDB is a reference to $usr, however $usr was just created by the foreach loop, and is is not referenced to the original array it is looping over. So say, for example, you have this very simple case:

    foreach ($foo as $var) {
        $var++;
    }
    

    This does NOT affect $foo at all.

    What you need to do is reference the $dataBase variable directly:

    foreach ($dataBase as $key => $usr) {
        if ($usr['id'] == $user['id']) {
            $userInDB = &$dataBase[$key];
            break;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)