2012-12-07 18 views
0

如何使用PHP向此對象添加更多字符串? 我已經設法生成字符串,但我不能將更多字符串添加到對象,也不能刪除最後一個逗號。使用PHP在對象中添加更多字符串

像這樣:

之前,

{ 
    "themes":[ 
    { 
     "name": "Amelia", 
     "description": "Sweet and cheery.", 
     "thumbnail": "http://bootswatch.com/amelia/thumbnail.png" 
     } 
    ] 
} 

後,

{ 
    "themes":[ 
      { 
     "name": "juan", 
     "description": "esto es un ejemplo.", 
     "thumbnail": "http://example.com" 
     }, 
       { 
     "name": "juan2", 
     "description": "esto es un ejemplo2.", 
     "thumbnail": "http://example2.com" 
     }, 
    ] 
} 

更新代碼:



    // $_POST = Request::post 
    if (Request::post('theme_title')) $theme_title = Request::post('theme_title'); else $theme_title = ''; 
    if (Request::post('theme_img')) $theme_img = Request::post('theme_img'); else $theme_img = ''; 
    if (Request::post('theme_desc')) $theme_desc = Request::post('theme_desc'); else $theme_desc = ''; 

    $jsonfile = 'events.json'; 

    $data->themes[] = (object)array(
     "name"  => $theme_title, 
     "description" => $theme_img, 
     "thumbnail" => $theme_desc 

    ); 

    $json = str_replace('\/','/',json_encode($data)); 

    // $_POST = Request::post 
    if (Request::post('Themes_add')){ 

      // file_put_contents 
     File::setContent($jsonfile, $json,$create_file = true, $append = true,); 
    } 

回答

0

「娟」,這很有趣。事情是這樣的:

$obj->themes[] = (object)array(
    "name"  => "juan2", 
    "description" => "esto es un ejemplo2.", 
    "thumbnail" => "http://example2.com" 
); 

乾杯

+0

謝謝,但這隻生成不能添加。 – Nakome

+0

然後你正在做其他事情。這裏,'$ obj'是你的頂級對象。只要這是正確的,這*會*將新條目添加到對象的'主題'數組中。 – Madbreaks

+0

另外,如果您希望人們繼續爲您提供幫助,請務必提高您認爲有幫助的答案。 – Madbreaks

1

我想這是絕對T A Dictionary對象,所以你可以這樣做:

obj["key1"] = []; 
obj["key2"] = []; 

{ 
    "themes":[ 
      { 
     "name": "juan", 
     "description": "esto es un ejemplo.", 
     "thumbnail": "http://example.com" 
     }, 
       { 
     "name": "juan2", 
     "description": "esto es un ejemplo2.", 
     "thumbnail": "http://example2.com" 
     }, 
    ], 
    "key1":[], 
    "key2":[] 
} 

或添加存儲在$親自到主題另一個對象鍵,您可以:

obj["themes"][] = $person; 
+0

咦?要麼你不明白這個問題,要麼我不知道。 :) – Madbreaks

+0

這可能我不明白這個問題。我以爲他想爲字典對象添加另一個關鍵字。但看看這個例子,我想你是對的,他想添加到主題列表中。 – ajon

+0

抱歉不瞭解。 – Nakome