[英]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.