检查属性是否在JSON中具有相同的值

时间:2016-10-27 00:11:51

标签: php json

鉴于以下json,我如何检查shipmentWay属性是否对每个父元素具有相同的值?

<link rel="stylesheet" href="..." />

我现在真的坚持这个,提前谢谢!

2 个答案:

答案 0 :(得分:0)

<?php
$json = '{
   "3":[
      {
         "idOrdenCompraProducto":3,
         "shipmentWay":"Confirmation Pending",
         "qty":25000
      }
   ],
   "4":[
      {
         "idOrdenCompraProducto":4,
         "shipmentWay":"Confirmation Pending",
         "qty":3000
      },
      {
         "idOrdenCompraProducto":4,
         "shipmentWay":"A\u00e9reo",
         "qty":1500
      },
      {
         "idOrdenCompraProducto":4,
         "shipmentWay":"Confirmation Pending",
         "qty":1000
      }
   ],
   "5":[
      {
         "idOrdenCompraProducto":5,
         "shipmentWay":"Confirmation Pending",
         "qty":25000
      },
      {
         "idOrdenCompraProducto":5,
         "shipmentWay":"Confirmation Pending",
         "qty":25000
      }
   ]
}';
$array = json_decode($json, true);
$shipmentWay = array();
foreach($array as $key => $parent)
{
  foreach($parent as $index => $child)
  $shipmentWay[$key][$child['shipmentWay']] = true; 
}
//    var_dump($shipmentWay);
    $result = array();
    foreach($shipmentWay as $key => $value)
    {
      $result[$key] = (count($value) > 1)?false:true;
    }
    var_dump($result);

演示参考https://eval.in/667231

输出

  

array(3){[3] =&gt; bool(true)[4] =&gt; bool(false)[5] =&gt;
  bool(true)}

答案 1 :(得分:0)

好吧我创建了this example

rename("user/image1.jpg", "user/del/image1.jpg");

您要查看的主要内容是函数function jsonAllSame($jsonStr) { $object = json_decode($jsonStr); foreach($object as $objArr) { $index = 0; $compare = ""; foreach($objArr as $obj) { if($compare == "") { $compare = $obj->shipmentWay; } else { if($obj->shipmentWay != $compare) { return false; } } } } return true; } $json = '{ "3":[ { "idOrdenCompraProducto":3, "shipmentWay":"Confirmation Pending", "qty":25000 } ], "4":[ { "idOrdenCompraProducto":4, "shipmentWay":"Confirmation Pending", "qty":3000 }, { "idOrdenCompraProducto":4, "shipmentWay":"A\u00e9reo", "qty":1500 }, { "idOrdenCompraProducto":4, "shipmentWay":"Confirmation Pending", "qty":1000 } ], "5":[ { "idOrdenCompraProducto":5, "shipmentWay":"Confirmation Pending", "qty":25000 }, { "idOrdenCompraProducto":5, "shipmentWay":"Confirmation Pending", "qty":25000 } ] }'; $compare = "Confirmation Pending"; var_dump(jSonAllSame($json)); 。它的作用是将json字符串作为参数。在函数内部,我们解码它然后循环它使用2个foreach循环创建的每个对象数组。

我们第一次通过对象数组(第二个foreach循环)时,我们无需比较,因此我们将jSonAllSame设置为我们看到的第一个值。

在第二次迭代中,因为$compare不为空,我们可以进行比较。如果我们找到一个不匹配的值,那么我们在那里停止函数并返回false,如果我们能够遍历每个对象数组而没有找到不匹配,那么我们返回true。

如果我们想要返回哪个数组第一个不匹配,假设数字与$compare的值匹配,那么我们将idOrdenCompraProducto替换为return false;