需要一些帮助来解决这个问题。在通过ajax单击提交后,我有一个JSON数组转到php文件。一旦在php端解码,它看起来像这样:
阵列
[0] => Array ( [ID] => 409 [ChangeType] => CHANGE_SEAT_TO [Name] => John Doe [Seat] => [setTo] => 4-2 [PreviousSeatValue] => [PreviousSeatNewValue] => Y ) [1] => Array ( [ID] => 278 [ChangeType] => CHANGE_SEAT_TO [Name] => John Test [Seat] => 4-1 [setTo] => 4-3 [PreviousSeatValue] => Y [PreviousSeatNewValue] => Y ) [2] => Array ( [ID] => 305 [ChangeType] => REMOVESEAT [Name] => John Blue [Seat] => 3-6 [setTo] => 0 ) [3] => Array ( [ID] => 314 [ChangeType] => CHANGE_SEAT_TO [Name] => John Red [Seat] => 3-4 [setTo] => 3-6 [PreviousSeatValue] => Y [PreviousSeatNewValue] => Y )
主要目标:
我尝试做的是遍历所有数组,如果changetype匹配字符串(“CHANGE_SEAT_TO”或“REMOVESEAT”),则执行SQL语句。我有问题在循环期间将变量分配给匹配数组中的不同键值。以下是我到目前为止的情况:
$obj = json_decode($_POST['myData'], TRUE);
foreach ($obj as $innerArray){
foreach($innerArray as $key => $value){
$$key = $value;
if($value === "CHANGE_SEAT_TO"){
echo $ID;
echo $setTo;
}
if($value === "REMOVESEAT"){
echo $ID;
echo $setTo;
}
}
}
现在显然这是为了测试目的而设置的(我在成功的ajax之后在控制台日志中显示了echo)。通过这种设置,我能够成功地回显匹配元素的ID,但如果我尝试任何其他元素,则变量是未定义的。任何人都可以解释为什么会这样,并提出一个主要目标的建议?提前谢谢。
答案 0 :(得分:1)
您只需要一个foreach()
,请检查修改后的代码
<?php
$obj = json_decode($_POST['myData'], TRUE);
foreach ($obj as $innerArray){
if($innerArray['ChangeType'] == 'CHANGE_SEAT_TO') {
// do stuff
$id = $innerArray['ID'];
// get rest of values in same way
} else if($innerArray['ChangeType'] == 'REMOVESEAT') {
// do stuff
$id = $innerArray['ID'];
// get rest of values in same way
}
}
答案 1 :(得分:0)
尝试这样的事情:
foreach ($obj as $value) {
if ($value['ChangeType'] == 'CHANGE_SEAT_TO') {
echo $value['ID'];
echo $value['setTo'];
} elseif ($value['ChangeType'] == 'REMOVESEAT') {
echo $value['ID'];
echo $value['setTo'];
}
}