2016-07-25 60 views
0

這是簡化版本的所有子陣列,我有一個數組裝滿物品,有時可能有重複遍歷數組和回聲具有相同的ID

$items = array(
    array(
     'id' => 1, 
     'title' => 'Item 1' 
     ), 
    array(
     'id' => 2, 
     'title' => 'Item 2' 
     ), 
    array(
     'id' => 3, 
     'title' => 'Item 3' 
     ), 
    array(
     'id' => 1, 
     'title' => 'Item 1' 
     ), 
    array(
     'id' => 3, 
     'title' => 'Item 1' 
     ), 
    array(
     'id' => 5, 
     'title' => 'Item 5' 
     ), 
    array(
     'id' => 3, 
     'title' => 'Item 1' 
     ), 
    ); 
?> 

我需要的是仔細檢查每一個項目,回顯它的標題,但是如果數組中有更多相同ID的項目,我需要通過當前項目回顯它們的標題邊並稍後跳過它們。

<ul> 
    <?php foreach($items as $item) : ?> 
     <li> 
      <?php echo $item['title']; ?> 
      <?php // check for other items and echo their titles if they are same 
     </li> 
    <?php endforeach; ?> 
</ul> 

最後,該示例應該站出來這樣

<li>Item 1 Item 1</li> 
<li>Item 2</li> 
<li>Item 3 Item 3 Item 3</li> 
<li>Item 5</li> 

如何解決它沒有做混亂有什麼想法? :)

我用這樣的東西玩,什麼地方呼應雙線..一般都不好

<?php $int = 0; ?> 
<?php foreach($items as $item) : ?> 
    <li> 
     <?php 
     echo $item['title']; 
     $id = $item['id']; 
     unset($items[$int]); 
     $int++; 

     foreach($items as $item_second) { 
      if($item_second['id'] === $id) { 
       echo $item_second['title']; 
       unset($item_second); 
      } 
     } 
     ?> 
    </li> 
<?php endforeach; ?> 

回答

2

有關呈現成二維陣列之前準備數組是什麼? 它會看起來是這樣的:

<?php 
    $itemsForRender = array(); 

    foreach ($items as $item) { 
     if (!isset($itemsForRender[$item['id']])) { 
      $itemsForRender[$item['id']] = []; 
     } 

     $itemsForRender[$item['id']][] = $item['title']; 
    } 
?> 

後,只是很容易:

<?php foreach($itemsForRender as $items) : ?> 
    <li> 
     <?php echo implode(' ', $items); ?> 
    </li> 
<?php endforeach; ?> 
+0

嗯HM ..我didnt't那裏去,因爲我的例子是相當有更多的數據和鏈接更復雜...我會尋找這個解決方案作爲一個計劃B :) –

+0

遇到什麼麻煩?也許我可以幫助:-)。 – pilec

+0

明天我會試着改變自己的密碼,所以我不會把事情搞砸,我會更清楚地思考:) –