PHP 没有正确迭代嵌套的 JSON


PHP not iterating through nested JSON properly

我正在尝试遍历包含三个嵌套 JSON 对象(NEWUSERSNEWUSERDATANEWRELATIONS(的 JSON 对象(DATA),使用开关函数为 MySQL 插入选择合适的函数。当我循环使用键时,开关中的每个函数都会被调用一次,但它们似乎都只接收NEWRELATIONS对象。因此,除了insertNewTestRelations之外,函数失败,该函数旨在接收NEWRELATIONS对象。我认为答案一定是盯着我的脸,但是有人能想到为什么要重用JSON对象吗?

读取和迭代 JSON

$json=json_decode($_SERVER['HTTP_JSON'],true);
$data=$json['DATA'];
foreach($data as $key=>$json_obj){
    $result=null;
    $result=$db->insertNewSwitch($key,$json_obj,$last_sync);
    $response[$key.":errors"]=$result['errors'];
    $response[$key.":successes"]=$result['successes'];
}

开关功能

public function insertNewSwitch($key,$json_obj,$last_sync){
    $result;
    if($key="NEWUSERS"){
        $result=$this->insertNewTestUsers($json_obj,$last_sync,$key);
    }
    if($key="NEWUSERDATA"){
        $result=$this->insertNewTestUserdata($json_obj,$last_sync,$key);
    }
    if($key="NEWRELATIONS"){
        $result=$this->insertNewTestRelations($json_obj,$last_sync,$key);
    }

    return $result;
}

尝试在逻辑运算符中使用 else 进行比较,并使用双等号进行比较

public function insertNewSwitch($key,$json_obj,$last_sync){
    $result;
    if($key=="NEWUSERS"){
        $result=$this->insertNewTestUsers($json_obj,$last_sync,$key);
    }
     else if($key=="NEWUSERDATA"){
        $result=$this->insertNewTestUserdata($json_obj,$last_sync,$key);
    }
    else if($key=="NEWRELATIONS"){
        $result=$this->insertNewTestRelations($json_obj,$last_sync,$key);
    }

    return $result;
}

您使用的是=而不是==。这很可能是你的问题。由于您正在分配值,因此每次的计算结果都将为 true,因此将输入每个语句。