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;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度