我正在尝试循环包含三个嵌套JSON对象((DATA)
,NEWUSERS
,NEWUSERDATA
)的JSON对象NEWRELATIONS
,使用切换功能选择合适的用于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;
}
答案 0 :(得分:3)
尝试在逻辑运算符中使用else作为开关,并使用double equals进行比较
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;
}
答案 1 :(得分:2)
您使用的是=
而不是==
。这很可能是你的问题。
因为您要分配值,所以每次都会评估为true,因此将输入每个语句。