【问题标题】:Using PHP / MySQLi to loop through json_decoded array not working for Update query使用 PHP / MySQLi 循环遍历 json_decoded 数组不适用于更新查询
【发布时间】:2020-08-09 10:38:25
【问题描述】:

我正在使用 json_decode() 来解码 Ajax 结果,该结果返回以下数组(缩短的示例)。 现在我想遍历这个区域并根据数组中的值更新每个 vId 的 rId 但这部分不起作用。

有人可以在这里告诉我如何正确执行循环部分(查询本身应该没问题)吗?

我的数组:

array(3) {
  [0]=>
  array(2) {
    ["vId"]=>
    string(8) "04567901"
    ["rId"]=>
    string(6) "DE-003"
  }
  [1]=>
  array(2) {
    ["vId"]=>
    string(8) "04567902"
    ["rId"]=>
    string(6) "DE-008"
  }
  [2]=>
  array(2) {
    ["vId"]=>
    string(8) "04567903"
    ["rId"]=>
    string(6) "DE-009"
  }
}

我的 PHP/MySQLi:

$postData = $_POST; 
$transferData = $_POST['transferData'];
$json = json_decode($transferData, true);

$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
    die("Connection Error: " . $conn->connect_error);
}   
$stmt = $conn->prepare("UPDATE locations l SET l.rId = ? WHERE l.vId = ?");
foreach($json as $vId => $rId) {
    $stmt->bind_param('ss', $rId, $vId);
    $stmt->execute();
}

$stmt->close();
$conn->close(); 

【问题讨论】:

标签: php arrays mysqli foreach


【解决方案1】:

在您的foreach 中,键是指数组的索引,而不是您认为的键。您的情况下的键实际上是 0, 1, 2, [...]。 你返回一个数组数组,所以得到你想要的部分如下:

foreach($json as $key => $value) {
    $stmt->bind_param('ss', $value['rId'], $value['vId']);
    $stmt->execute();
}

【讨论】:

  • 非常感谢 - 这正是我做错的。完美运行。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-23
  • 2015-09-26
  • 1970-01-01
  • 2011-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多