2015-10-15 165 views
0

我有一個JSON數組新元素添加到JSON數組

{ 
    "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" 
    } 
} 

,我得到了一個PHP腳本,獲取輸入值將新元素從上面我不知道這是否是推到JSON數組oke,但是當我嘗試推送它時,我得到一個0,輸入值在它旁邊。

<?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); 
      } 
    ?> 
+0

它不是一個JSON數組,它是一個哈希值。你不應該推入它 - 但設置適當的價值新鑰匙。 – Alex

+0

你不添加到JSON。您將json解碼爲本地結構,將新的東西添加到該結構中,然後重新編碼爲json。你擁有的不是一個數組('[[...]')。你有一個對象('{...}')。 –

+0

http://pastebin.com/Q7Eqve1K –

回答

2

如果這真是一個JSON數組,你應該嘗試的字符串解碼成數組:

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

然後就推新元素到數組? 最後,你可以做

<?php 
$list = json_encode($decoded_list); 
?> 
0
$str = $url.":{"."domain:".$t_d.","."template:".$t_t."},"; 
$str = json_decode($str); 

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

首先,解碼你的JSON:

$list = json_decode($list, true); 

然後,創建你的用戶輸入值的數組(下面簡單的例子):

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

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

追加數據:

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

最後,編碼回JSON像這樣:

$json = json_encode($data); 

輸出:

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