Home > Software engineering >  I am not able to pass themultiple data php array to json string list ."subnet_name":"
I am not able to pass themultiple data php array to json string list ."subnet_name":"

Time:11-30

I need to pass the multiple data in one json list Sample payload

"resourcegroup_name":"phpvnet",
"location":"Centralus",
"virtual_network_name":"demophpvnet",
"vnetAddressPrefix":"10.0.0.0/16",
"subnet_count":"2",
"subnet_name":"[\"phpsubnet\",\"testsubnet\"]",
"address_prefix":"[\"10.0.1.0/24\",\"10.0.2.0/24\"]"

and the php and json data i am passing is

if(isset($_POST['insert'])){

    $provisionId = "cloudknit".substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 6);
    $rgname = $_POST['rgname'];
    $location = $_POST['location'];
    $vnetname = $_POST['vnetname'];
    $vnetaddress = $_POST['vnetaddress'];
    $subnetcount = $_POST['subnetcount'];
    $subnetname = $_POST['subnetname'];
    $addressprefix = $_POST['addressprefix'];

      echo json_encode(array($col,$col2));

      $data = array(
      "provisionId"=>"$provisionId",
      "resourcegroup_name"=>"$rgname",
      "location"=>"$location",
      "virtual_network_name"=>"$vnetname",
      "vnetAddressPrefix"=>"$vnetaddress",
      "subnet_count"=>"$subnetcount",
      "subnet_name"=>"$subnetname",
      "address_prefix"=>"$addressprefix"
      );

I need to pass the data from php to json list in subnet name and address prefix.

CodePudding user response:

I just got an answer. if you want the string in json encode format whenever the json has multiple data list use this

'''

  $json = [
    'subnet_name'  => json_encode(explode(",", $subnetname))
  ];
  
  $json1 = [
    'address_prefix'  =>  json_encode($addres_fix, JSON_UNESCAPED_SLASHES)
  ];

'''

CodePudding user response:

You need to use json_decode() function first to convert the string to a PHP list/array then you can assign the returned value to "subnet_name" field in your new array,I hope this piece of code would help you:

<?php
          
$subnetname="[\"phpsubnet\",\"testsubnet\"]";
$json = [
   'subnetname'  => json_decode($subnetname)
];

var_dump($json);

EDITTED:

$data = array( "provisionId"=>"$provisionId", 
"resourcegroup_name"=>"$rgname", 
"location"=>"$location", 
"virtual_network_name"=>"$vnetname", 
"vnetAddressPrefix"=>"$vnetaddress", 
"subnet_count"=>$subnetcount, 'subnetname' => explode(",", $subnetname), 
"address_prefix"=>"$addressprefix" 
); 
  • Related