2017-04-11 67 views
0

這裏數組項旁邊添加另一個數組項我有一個包含基本的評論值如何在一個特定的值時

//cid is comment id and pid is parent id 
$comments = array(
       array(
       'cid' = '47', 
       'pid' = '0', 
       'comment' = 'This is comment' 
      ), 
       array(
       'cid' = '48', 
       'pid' = '0', 
       'comment' = 'This is another comment' 
      ), 
       array(
       'cid' = '49', 
       'pid' = '47', 
       'comment' = 'This is child comment to parentID 47' 
      ), 
      ); 

我想最終的結果是,有任何評論陣列項的嵌套數組一個parentID應該在與該父ID相匹配的commentID之後重新定位自己。爲了使其可視化,具有父項的註釋數組是對原始註釋的回覆。到目前爲止,我管理這個多

//main loop 
foreach ($comments as $index => $val) { 

    $cids[] = $val['cid']; 

    if($val['pid'] > 0) { 
     foreach ($cids as $cidindex => $cid) { 

      if($val['pid'] == $cid) { 
       $results[$index] = $val; 
       $results[$index + 1] = _comment_load($cid, $array); 
      } 
     } 
    } 
    else { 
     $results_ano[$index] = $val; 
    } 
}//end of main loop 

//loads comment 
function _comment_load($cid, $array) { 
    foreach ($array as $Key => $item) { 
     if($item['cid'] == $cid) { 
      return $item; 
     } 
    } 
} 

因此合併$results$results_ano我得到print_r

Array 
(
    [2] => Array 
     (
      [pid] => 47 
      [cid] => 49 
     ) 

    [3] => Array 
     (
      [pid] => 0 
      [cid] => 47 
     ) 

    [0] => Array 
     (
      [pid] => 0 
      [cid] => 47 
     ) 

    [1] => Array 
     (
      [pid] => 0 
      [cid] => 48 
     ) 
) 

我還是設法得到我想要的東西稍微但是,現在commentId = 47被重複後,我想了重複cid項目數組以從結果數組中移除。

+0

是否有任何特別的東西強迫您以特定的順序需要該數組,無法通過多個數組實現? – m4grio

+0

謝謝,作爲父ID的數組項目是對評論ID的回覆,這使得模板更容易模板化。 –

回答

0

我管理由「主循環」

foreach ($results as $key => $value) { 
     foreach ($results_ano as $anokey => $anovalue) { 
     if($anovalue['cid'] == $value['cid']) { 
     //Ignore Everything in here 
     }else { 
      $finalresults[] = $anovalue; 
     } 
    } 
    } 

    $merge = $results = $finalresults; 

這使我沒有這種重複項目的陣列後具有下列實現這一目標。

相關問題