这是我的PHP代码,
<?php
$query = "SELECT items FROM `ppmp` ORDER BY date DESC LIMIT 1";
if($result2 = $con->query($query)) {
$row = $result2->fetch_array();
$items2 = $row['items'];
}
$items = $_POST['ris4'];
$items = json_decode($items,true);
$items2 = json_decode($items2,true);
for($i = 0; $i < sizeOf($items["items"]);$i++){
for($i2 = 0; $i2 < sizeOf($items2["items"]); $i2++){
$val = $items["items"][$i]["Desc"];
$val2 = $items2["items"][$i2]["Desc"];
print_r($val);
print_r($val2);
if(strcmp($val, $val2) == 0){
echo "same";
}
}
}
?>
我要减去产品的数量..但我无法检测这两个描述是否相同..
我使用strcmp()
但它不起作用..我回应描述,它有相同的描述。但是==
运营商没有工作。
这是$items2
JSON的布局,
{"items":[{"Desc":" Pencil ","Qty":25},{"Desc":" Ballpen ","Qty":5},{"Desc":" Tech Pen ","Qty":20}]}
这是$items
,
{"items":[{"Desc":" Tech Pen ","Qty":15},{"Desc":" Ballpen ","Qty":4}]}
我建议你使用array_diff
。这样您就可以确保它们与JSON
结构中的内容完全匹配。
$it_1 = json_decode($items, TRUE);
$it_2 = json_decode($items2, TRUE);
$result_array = array_diff($it_1,$it_2);
if(empty($result_array[0])){
echo "they are same";
}
假设我们......
JSON OBJ 1 {“key1”:“message”,“key2”:“message”,“key3”:“message”}
JSON OBJ 2 {“key2”:“message2”,“key3”:“message3”,“key1”:“message1”}
使用像这样的代码:
$responseMatch = json_decode($obj1) == json_decode($obj2);
return $responseMatch ? 'responses match!' : 'responses dont match!';
会给你你想要的东西,我已经在很多用例中测试过了
试试这个。
$items1 = json_decode('{"items":[{"Desc":" Tech Pen ","Qty":15},{"Desc":" Ballpen ","Qty":4}]}');
$items2 = json_decode('{"items":[{"Desc":" Pencil ","Qty":25},{"Desc":" Ballpen ","Qty":5},{"Desc":" Tech Pen ","Qty":20}]}');
for($i=0;$i<count($items1->items);$i++){
for($j=0;$j<count($items2->items);$j++){
$val = $items1->items[$i]->Desc;
$val2 = $items2->items[$j]->Desc;
if($val == $val2){
$items2->items[$j]->Qty -= $items1->items[$i]->Qty;
}
}
}
print_r($items2);
会输出
[items] => Array
(
[0] => stdClass Object
(
[Desc] => Pencil
[Qty] => 25
)
[1] => stdClass Object
(
[Desc] => Ballpen
[Qty] => 1
)
[2] => stdClass Object
(
[Desc] => Tech Pen
[Qty] => 5
)
)
假设您的'Desc'是纯文本字符串,您可以通过以下方式检查这些:
if (strcmp($val, $val2) !== 0) {
//they are not the same
}
更新:
$items1 = json_decode('{"items":[{"Desc":" Tech Pen ","Qty":15},{"Desc":" Ballpen ","Qty":4}]}');
$items2 = json_decode('{"items":[{"Desc":" Pencil ","Qty":25},{"Desc":" Ballpen ","Qty":5},{"Desc":" Tech Pen ","Qty":20}]}');
for($i=0;$i<count($items1->items);$i++){
for($j=0;$j<count($items2->items);$j++){
$val = $items1->items[$i]->Desc;
$val2 = $items2->items[$j]->Desc;
if( strcmp($val, $val2) == 0 ){
echo "Item ".$val." match with ".$val2." ";
//$items2->items[$j]->Qty -= $items1->items[$i]->Qty;
}else{
echo "Item ".$val." don't match with ".$val2." ";
}
}
}
你说这不起作用,但我在我的localhost上测试这个并且工作正常。