D. Ronald
D. Ronald

Reputation: 51

Add new element to Json array

I got a Json Array

{
  "cms18.test.silverbee.nl": {
    "domain": "cms18",
    "template": "default"
  },
  "dmmd.test.silverbee.nl": {
    "domain": "dmmd",
    "template": "default"
  },
  "opmaat.test.silverbee.nl": {
    "domain": "opmaat",
    "template": "opmaat"
  },
  "opmaatdebiteurenadvies.nl": {
    "domain": "opmaat",
    "template": "opmaat"
  },
  "navbar.test.silverbee.nl": {
    "domain": "navbar",
    "template": "default"
  },
  "test18.test.silverbee.nl": {
    "domain": "test18testsilverbeenl",
    "template": "test"
  },
  "huisartsplus.test.silverbee.nl": {
    "domain": "huisartsplustestsilverbeenl",
    "template": "huisartsplus"
  },
  "robertenrademaker.test.silverbee.nl": {
    "domain": "robertenrademakertestsilverbeenl",
    "template": "robert-en-rademaker"
  },
  "tilburg.test.silverbee.nl": {
    "domain": "tilburgtestsilverbeenl",
    "template": "default"
  },
  "cbk-groningen.test.silverbee.nl": {
    "domain": "cbk_groningentestsilverbeenl",
    "template": "cbk-groningen"
  },
  "getbusyinc.test.silverbee.nl": {
    "domain": "getbusyinctestsilverbeenl",
    "template": "getbusyinc"
  }
}

And i got a Php script that gets input values to push a new element to Json array from above i dont know if this is oke but when i try to push it i get an 0 with the input values next to it.

 <?php 
    $url = $_POST['new_url'];
    $t_d = $_POST['t_d'];
    $t_t = $_POST['t_t'];
    $str = $url.":{"."domain:".$t_d.","."template:".$t_t."},";
          if (isset($url)) 
          {
            array_push($list, $str);
          }
    ?>

Upvotes: 0

Views: 528

Answers (3)

Chris Rowles
Chris Rowles

Reputation: 120

First, decode your json:

$list = json_decode($list, true);

Then, create an array from your user input values (basic example below):

$url = "google.com";
$t_d = "google";
$t_t = "googletwo";

$data[] = $url;
$data[] = array('domain' => $t_d, 'template' => $t_t);

Append the data:

if(isset($url)){
    array_push($temp, $data);
}

Finally, encode it back to json like so:

$json = json_encode($data);

output:

[
  "google.com",
  {
    "domain": "google",
    "template": "googletwo"
  }
]

Upvotes: 0

simi
simi

Reputation: 36

If it's really a json array you should try decode the string into array:

<?php 
$decoded_list = json_decode($list, true); 
?>

then just push the new element into the array? Finally you can do

<?php 
$list = json_encode($decoded_list); 
?>

Upvotes: 2

Vishu238
Vishu238

Reputation: 673

$str = $url.":{"."domain:".$t_d.","."template:".$t_t."},";
$str = json_decode($str);

          if (isset($url)) 
          {
            array_push($list, $str);
          }

Upvotes: 0

Related Questions