user3720752 user3720752 - 1 month ago 7
JSON Question

Check if property has the same value in JSON

Given the following json, how can I check if shipmentWay property have the same value for each parent element?

{
"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
}
]
}


I'm really stuck with this right now, thanks in advance!

Answer
<?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);

demo refer to https://eval.in/667231

the output is

array(3) { [3]=> bool(true) [4]=> bool(false) [5]=>
bool(true) }