Tuesday, 28 August 2018

PHP json does not show all related values

Hello I have this php code for printing json

<?php

include('databaseconnect.php');

$sql = "SELECT product_id,product_name FROM products WHERE product_id='1'";
$result = $conn->query($sql);

$sql2 = "SELECT GROUP_CONCAT(ss.Name,':',sv.value_s ) as Specifications FROM specifications ss, specification_value sv WHERE sv.specification_ID = ss.specification_ID AND sv.product_id =  '1'";
$fetch = $conn->query($sql2);

$sql3 = "select GROUP_CONCAT(v.name,':',vv.value) as variants from variant v,variant_value vv where v.variant_id=vv.variant_id and product_id='1'";
$fetch1 = $conn->query($sql3);

$json['products'] = array();

while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){

    $json['products'] = $row;

  }

$json['products']['specification'] = array();

while ($row = mysqli_fetch_assoc($fetch)){

    $specification_array  = explode(',', $row["Specifications"]);
    $speci_array = array();
    foreach($specification_array as $spec){
        $spec = explode(':',$spec);
        $speci_array[$spec[0]] = $spec[1];
    }
    $json['products']['specification'] = $speci_array;

    //array_push($json['products'],$row_temp);
   }

$json['products']['specification']['variants'] = array();

while ($row = mysqli_fetch_assoc($fetch1)){

    $variants_array  = explode(',', $row["variants"]);
    $vari_array = array();
    foreach($variants_array as $var){
        $var = explode(':',$var);
        $vari_array[$var[0]] = $var[1];
    }
    $json['products']['specification']['variants'] = $vari_array;

    //array_push($json['products'],$row_temp);
   }

echo Json_encode($json);

?>

and output of this is
{
    "products": {
        "product_id": "1",
        "product_name": "Face Wash",
        "specification": {
            "brand": "Python",
            "product_Description": "very good",
            "variants": {
                "size": "long"
            }
        }
    }
}

but in this i have one more value for variant i.e. "size":"small" and that is not showing up. sorry for bad English please ask me for any clarification before answering
my desired output
{
    "products": {
        "product_id": "1",
        "product_name": "Face Wash",
        "specification": {
            "brand": "Python",
            "product_Description": "very good",
            "variants": {
                "size": "small"
                "size": "long"
            }
        }
    }
}


You can't add same key size twice. The previous key gets overwritten by later.

0 comments:

Post a Comment