Saturday, August 20, 2016

JSON encode Decode in anonymous format


<?php
function jsonencode($str){
$retvar='';
$str1=str_replace("-",",",$str);
$val1=explode(",",$str1);
$cnt=count($val1);
if($cnt%2==0){
if($cnt==2)
$retvar='[{"qty":"'.$val1[0].'","price":"'.$val1[1].'"}]';
elseif($cnt==4)
$retvar='[{"qty":"'.$val1[0].'","price":"'.$val1[1].'"},{"qty":"'.$val1[2].'","price":"'.$val1[3].'"}]';
elseif($cnt==6)
$retvar='[{"qty":"'.$val1[0].'","price":"'.$val1[1].'"},{"qty":"'.$val1[2].'","price":"'.$val1[3].'"},{"qty":"'.$val1[4].'","price":"'.$val1[5].'"}]';
elseif($cnt==8)
$retvar='[{"qty":"'.$val1[0].'","price":"'.$val1[1].'"},{"qty":"'.$val1[2].'","price":"'.$val1[3].'"},{"qty":"'.$val1[4].'","price":"'.$val1[5].'"},{"qty":"'.$val1[6].'","price":"'.$val1[7].'"}]';
else
$retvar="Invalid Storage";
}
return $retvar;
}

function jsondecode($str){
$cnt=substr_count($str,"qty");
$str1=str_replace('[{"qty":"',"",$str);
$str2=str_replace('"}]',"",$str1);
$str3=str_replace('","price":"',"-",$str2);
$str4=str_replace('"},{"qty":"',",",$str3);
return $str4;
}

$str="1-2,3-4,5-6,7-8";
echo jsonencode($str);


$str='[{"qty":"500","price":"43"},{"qty":"1000","price":"80"},{"qty":"1000","price":"80"}]';
echo jsondecode($str);
?>

No comments:

Post a Comment

Dharamart.blogspot.in