2015-09-02 94 views
0

我是新來的PHP,並試圖產生以下JSON輸出:Array對象的PHP

{ 
    "contacts": [ 
    { 
     "id": "1", 
     "name": "John Bob", 
     "email": "[email protected]" 
    }, 
    { 
     "id": "2", 
     "name": "Johnny Mac", 
     "email": "[email protected]" 
    }, 
     ..... 
    ] 
} 

,我有下面的PHP代碼:

$final = array(); 
foreach ($contacts as $contact) 
{ 
    ..... 
    $final[] = array(
     'id'   => (string)$id, 
     'name'   => $name, 
     'email'  => $email 
    ); 
} 
header('Content-Type: application/json; charset=UTF-8'); 
echo json_encode($final, JSON_PRETTY_PRINT); 
然而

,此輸出:

[ 
    { 
    "id": "1", 
    "name": "John Bob", 
    "email": "[email protected]" 
    }, 
    { 
    "id": "2", 
    "name": "Johnny Mac", 
    "email": "[email protected]" 
    }, 
] 

我讀了this tutorial,改變$final[]$final['contacts']但ST生病無法產生所需的json文件。

回答

0

或者:

$final['contacts'][] = array(..); 

或:

$contacts_output = array(); 
foreach ($contacts as $contact) { 
    $contacts_output[] = array(..); 
} 
$final = array('contacts' => $contacts_output); 
echo json_encode($final, JSON_PRETTY_PRINT); 
+0

謝謝第一種方法解決了這個問題。你能解釋爲什麼嗎? – semangi

+0

因爲它增加了一個你需要的更多密鑰和數組的額外等級......! – deceze

0
foreach ($contacts as $contact) 
{ 
    ..... 
    $final['contacts'][] = array(
      array(//insert all your array in contacts 
       'id'  => (string)$id, 
       'name'  => $name, 
       'email' => $email 
    ); 
} 
+0

@semagi可你給我的print_r($觸點)? – aldrin27

+0

這產生這個輸出http://pastebin.com/ff5GxDfE這是不正確的 – semangi

+0

我已經更新了現在 – aldrin27

0

試試這個:

$final = array(); 
$final['contacts'] = array(); 
foreach ($contacts as $contact) 
{ 
    ......... 
    $final['contacts'][] = array( 
    'id'  => (string)$id, 
    'name'  => $name, 
    'email' => $email 
); 
} 
0
$final = array('contacts'=>[]); 

foreach ($contacts as $contact) 
{ 
    $final['contacts'] []= 
      array(//insert all your array in contacts 
       'id'  => (string)$id, 
       'name'  => $name, 
       'email' => $email 
      ); 
}