[英]Foreach Loop and if statement using PHP
I want to edit a JSON object, so made method called alterJSON
the function find the specific JSON array
from the database and then change the key-values
based on the parameters was given so my question is as you can see in this foreach loop there is一个(if statement)
foreach( $decoded as $index => $product ){
print_r('<pre>');
if( $product->$key == $item) {
echo ('found');
$decoded[ $index ]->$key = $value;
$json = json_encode( $decoded );
$stmt->execute([
':json' => $json,
':id' => $bid
]);
}
}
该循环将通过MySQL
查询打印found
并在$JSON
上进行一些更改,这是完美的工作,但它只会找到 JSON object or item
,即使有相同key-value
然后item
在statement
中创建另一个条件来检查名为id
的唯一key-value
那么我该如何实现呢? 我做了一些尝试,但失败了。
我试过的
<?php
public function AlterJSON( $bid=false, $item=false, $key=false, $Product, $id, $value=false ){
try{
if( $bid && $item && $key && $value && $Product && $this->connected === true ){
$stmt=$this->connection->prepare('select `items` from `bills` where `id`=:id');
$stmt->execute( [ ':id' => $bid ] );
$fetched = $stmt->fetchColumn();
$decoded = json_decode( $fetched );
$stmt=$this->connection->prepare('update `bills` set `items`=:json where id=:id');
foreach( $decoded as $index => $product ){
print_r('<pre>');
if( $product->$key == $item && $product->$id == $Product) {
echo ('found');
$decoded[ $index ]->$key = $value;
$json = json_encode( $decoded );
$stmt->execute([
':json' => $json,
':id' => $bid
]);
}
}
return true;
}
return false;
} catch( PDOException $e ){
return $this->errors === true ? $this->error( $e->getMessage() ) : false;
}
}
?>
function call:-
$call = $dbConnection->AlterJSON( $BillID, $CurrentPrice,'price', $ProductID,'id', $ProductPrice );
您是否尝试过简单地将$stmt=$this->connection->prepare
放入foreach
循环中?
请确定,function AlterJSON
有一个变量$Product
但是当你调用这个AlterJSON
你使用$ProductID
,你可以对两个变量都使用$ProductID
吗? PHP 对变量区分大小写。 所以它很好,但我的可读性更好。
if( $product->$key
if $key
not exist in $product
中的其他技巧会产生错误。是的,你有一个 try catch,但如果替换在 N 循环中,你将失去此更新的可能性。我会在$product->$key
之前安装保护,以确保密钥存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.