2013-08-22 125 views
0

你好我無法弄清楚如何遍歷這個json編碼數組,併爲每個對象,獲取它的所有值。我需要將每個值作爲自己的變量。json_encode獲取值foreach對象

echo json_encode($formulars); 

這是我所得到的,當我贊同它

[{"project_name":"polle","type":"support","title":"vi","reason":"prover","solution":"igen","comments":"okay ","date_stamp":"2013-08-20 14:06:37","used_time":132},{"project_name":"dolla","type":"support","title":"lolol","reason":"skl","solution":"dskal","comments":"kflafda ","date_stamp":"2013-08-20 14:11:36","used_time":210},{"project_name":"polle","type":"fejl","title":"lol","reason":"aksdl","solution":"fdjks","comments":"djsks ","date_stamp":"2013-08-20 14:13:27","used_time":1230}] 

我已經試過這段代碼,我設法脫身,從第一個對象的PROJECT_NAME,這就是它:

foreach ($formulars as $current => $project_name) { 
     $project_name['project_name']; 

    } 

那麼,有什麼辦法可以讓每個對象中的所有變量我的數組而不僅僅是PROJECT_NAME的?

像這樣:

foreach ($formulars as $current){ 
    $projectName = $current['project_name']; 
    $type = $current['type']; 
    $reason = $current['reason']; 

} 

在此先感謝

+1

嘗試json_decode(),那麼你可以訪問它。 – Parixit

+0

「像這樣:」代碼似乎就足夠了。爲什麼它不工作?發生了什麼? – mario

+0

哦,上帝馬里奧我竟然沒有測試出「這樣」的代碼,我只是快速輸入了它。我只是試了一下,它的工作。我覺得很愚蠢,呵呵。謝謝你! –

回答

0

好像你有一個數組內的對象。所以你需要遍歷數組並獲取每個對象。只需JSON_DECODE你的編碼字符串如下。

也許:

$data = json_decode($formulars,true); 
/* Since it's only one object inside the array, you could just select element zero, but I wil loop*/ 

//You should now be able to do this 
foreach ($data as $current){ 
    $projectName = $current['project_name']; 
    $type = $current['type']; 
    $reason = $current['reason']; 

} 

我之所以環是因爲有一個數組(使用Javascript方式,我認爲)內的對象。

+0

我試圖使用json_decode,但它不會讓我。我得到這個消息:警告:json_decode()期望參數1是字符串,數組給出 –

+0

@ Alex.M.K哦...那麼這意味着你可以跳過解碼步驟,因爲它不再是json字符串。這是一個數組(可能在某處解碼)。你可以跳到foreach步驟。或者在這種情況下使用元素零。而是循環通過它。 – Touch

1

使用json_decode到JSON對象轉換爲陣列;然後使用foreach循環訪問陣列。這應該工作。

<?php 
    $arr_json = json_decode($formulars); 
    foreach($arr_json as $key => $value) 
     //Code to perform required actions 
?> 

這應該給你一些想法。

0

使用json_decode(與TRUE獲取關聯數組)將您的JSON對象轉換爲關聯數組。之後,您可以使用foreach循環遍歷多維數組並打印所需的值。

代碼:

$json = json_decode($string, true); 

foreach ($json as $key => $value) { 
    foreach($value as $key2 => $value2) { 
    echo $value2."\n"; 
    } 
} 

Working Demo!