2011-04-28 29 views
1

我已經做了一千次之前,但由於某種原因,我不能使用他們的索引/鍵訪問數組條目。我所做的唯一不同的是從文件中讀取json,然後使用json_decode來填充這個特定的對象數組。當我使用foreach循環時,我得到了$ post和$ key,但是當我用$ posts [$ key]訪問原始數組中的相同值時,它不會返回任何內容。我需要取消一些特定的條目,並通過參考傳遞也沒有幫助。下面是代碼:無法使用PHP中的索引/鍵訪問數組條目使用其中的索引/鍵PHP

$contents = fread($fh, filesize($filepath)); 
    fclose($fh); 
    $posts = (array)json_decode($contents); 

    foreach($posts as $key => &$post){ 
     $post_time = strtotime($post->post_date); 
     $now = strtotime('now'); 
     if(($now - $post_time) > 86400){ 
      unset($posts[$key]); 
     } 
    } 
+0

'print_r($ posts)'返回什麼? – Ikke 2011-04-28 08:04:23

+0

用'print_r($ posts)'檢查結構並嘗試'json_decode($ contents,true)'。 – 2011-04-28 08:04:33

+0

''無形的JSON! – 2011-04-28 08:04:42

回答

7

變化

$posts = (array)json_decode($contents);

$posts = json_decode($contents, true); - 它會回報你需要數組。

http://ru2.php.net/manual/en/function.json-decode.php

也可以改變$now = strtotime('now');$now = time();並將其移出循環 - 它的速度更快:)

TNX @binaryLV的提示:)

+0

也許試圖解釋他爲什麼需要改變這種方式 – Ikke 2011-04-28 08:07:36

+0

@Ikke更好? :) – Emmerman 2011-04-28 08:09:21

+0

我會建議使用'time()'而不是'date()'...或者甚至更好 - '$ _SERVER ['REQUEST_TIME']' – binaryLV 2011-04-28 08:10:47

0

如果我記得沒錯,json_decode沒有按默認返回一個數組,但是是一個對象。如果你想對它進行foreach(),你必須明確地要求它返回一個數組。

+0

謝謝。這確實是問題。 – 2011-04-28 08:13:36