Categories

simplyfying and accessing json data with php

<html>
<head>
<title>Online PHP Script Execution</title>
</head>
<body>
<?php
   
   
   $apple ='{
"title" : "Apple",
"description": "APple is fruit",
"weight": 1,
"SKU": "12",
"Quantity": 15,

"variation":[{
      "color":"red",
      "size" : "large",
      "price": 100
      },
 {

      "color":"gree",
      "size" : "small",
      "price": 50
  
      }  

  ]
}';

$mango = json_decode($apple);

$fruit = array();
$variationlist = array();
$variationarray = array();
foreach($mango as $key=>$value)
{
    if(!is_array($value)){
         $fruit[$key] = $value;  // pushes data upto quantity and not the variation
    }
  
   if(is_array($value)){
       
       foreach($value as $variation){
           
           if(is_array($variation)){
               foreach($variation as $variationKey=>$variationValue){
                    $variationarray[$variationKey] = $variationValue;
       
               }
              
           }
           array_push($variationlist, $variation);  
           $variationarray = array();
       }
   }
}


print_r($variationlist);
echo "content of $fruit<br>";
print_r($fruit);



?>
</body>
</html>


OUTPUT

<?php
   $data ='{
    "title" : "Apple",
    "description": "APple is fruit",
    "weight": 1,
    "SKU": "12",
    "Quantity": 15,

    "variation":[{
       "attribute_color":"red",
       "attribute_size" : "large",
       "_price": 100
       },
     {

       "attribute_color":"gree",
       "attribute_size" : "small",
       "_price": 50
      
       }  

      ]
    }';
    
  $dataArray = json_decode($data);
 
        foreach($dataArray as $key=>$value)
     { 
                if(is_array($value)){
    foreach($value as $variationKey=>$variationValue){
               
       echo "out"." ";
                
          foreach($variationValue as $lastkey=>$lastvalue){
               echo $lastkey. " => " .$lastvalue. " , ";
             }
             
          
             }

       
        }
   }
 

 
?>

echo “out” is for outer loop and in inner loop lastkey and lastvalue is printed

adbanner