2012-11-24 124 views
1

我已經做了相當的谷歌搜索,找不到任何有用的東西,我只是沒有得到任何回報,這可能是簡單的東西,但有很多變化,看起來不符合我所做的。在一個循環中創建一個多維數組php

爲了給你一個總體想法,我正在訪問一個API並獲取作爲對象的信息。有評論和附件,這些是分開的陣列。

我想要做的是按照日期和時間順序顯示評論和附件,而不是單獨顯示。

我想最好的方法是通過comments數組創建一個循環,然後通過附件數組創建一個循環,然後加入並按日期排序(epoch),然後循環遍歷整個合併循環,回顯我的內容想。這應該提供一些上下文,現在我只是想創建多維數組的評論,我可以找出其餘的。

$comments_holder = array(); 

//total number of comments in the array  
$comment_total = $issue_json->fields->comment->total -1; 
$i=1; 
while ($i <= $comment_total) 
    { 
    //this is the date,time and timezone info for each comment 
    $raw_date = $issue_json->fields->comment->comments[$i]->updated; 

    $comments_holder[$i] = array(); 

    //convert_sql_time just converts from 2012-11-04T16:33:00.936+600 into epoch time so i can sort the results later based on date 
    $comments_holder[$i]['comments_date'] = convert_sql_time($raw_date); 
    $comments_holder[$i]['comments_displayName'] = $issue_json->fields->comment->comments[$i]->author->displayName; 
    $comments_holder[$i]['comments_body'] = $issue_json->fields->comment->comments[$i]->body; 
    } 
+1

那麼是什麼問題? – arkascha

+1

我沒有看到'$ i ++' –

+0

使用'foreach'來迭代槽數組。 http://php.net/manual/en/control-structures.foreach.php –

回答

3

,如果一切正常的數據,這個代碼就足夠建立這樣的陣列:

$comments = $issue_json->fields->comment->comments; 
$result = array(); 

foreach ($comments as $comment) { 
    $result[] = array(
    'comments_date' => convert_sql_time($comment->updated), 
    'comments_displayName' => $comment->author->displayName, 
    'comments_body' => $comment->body, 
); 
} 

print_r($result); 
  • 如果comment->評論是一個數組,就沒有必要保留它的計數分別;
  • foreach對於遍歷數組是足夠的,並且不需要爲計算數組索引保留單獨的變量;
  • []符號將自動增加數組索引和分配陣列直接將這樣的伎倆(即,將導致到多維數組)
+0

完美作品,非常感謝 – user1547410