2012-01-27 59 views
0

我正在PHP中構建一種lifestream-esque博客類型的博客。它從我的MySQL數據庫,以及我的推文和我的Last.fm記錄中提取我的博客文章。將數組元素組合到一個單獨的元素中,直到某個點

到目前爲止這麼好,但我想將多個後續的音樂合併爲一個。儘管如此,如果一篇博文或一條推文打破了一連串的音樂記錄,那麼鏈條的第二部分不能與第一部分相結合。

Array 
(
    [0] => Array 
     (
      [contents] => Disturbed 
      [type] => scrobble 
      [published] => 1327695674 
     ) 

    [1] => Array 
     (
      [contents] => Amon Amarth 
      [type] => scrobble 
      [published] => 1327695461 
     ) 

    [2] => Array 
     (
      [contents] => Apocalyptica 
      [type] => scrobble 
      [published] => 1327693094 
     ) 

    [3] => Array 
     (
      [contents] => This is a tweet. Really. 
      [type] => tweet 
      [published] => 1327692794 
     ) 

    [4] => Array 
     (
      [contents] => Dead by Sunrise 
      [type] => scrobble 
      [published] => 1327692578 
     ) 
) 

所以由於[3]是一條推文,因此應該將scrobbles [0] - [2]合併爲一個元素。時間戳[published]應該設置爲最近的組合元素,並且[contents]字符串將使用逗號放在一起。但[4]不能成爲組合的一部分,因爲這會破壞事物的時間順序。

如果你仍然和我在一起:我想我可以使用大量的迭代和條件等,但我不確定如何處理與性能有關的事情。任何陣列特定的功能,我可以使用?

回答

0
$posts = array(/* data here: posts, tweets... */); 
$last_k = null; 

foreach($posts as $k => $v) 
{ 
    if((null !== $last_k) && ($posts[ $last_k ][ 'type' ] == $v[ 'type' ])) 
    { 
     $posts[ $last_k ][ 'contents' ][] = $v[ 'contents' ]; 
     $posts[ $last_k ][ 'published' ] = max($posts[ $last_k ][ 'published' ], $v[ 'published' ]); 
     unset($posts[ $k ]); 
     continue; 
    } 
    $posts[ $k ][ 'contents' ] = (array)$v[ 'contents' ]; 
    $last_k = $k; 
} 

因爲'contents'索引是數組,所以您將不得不爲輸出使用連接函數。 贊:

foreach($posts as $v) 
{ 
    echo '<div>', $v[ 'type' ], '</div>'; 
    echo '<div>', $v[ 'published' ], '</div>'; 
    echo '<div>', join('</div><div>', $v[ 'contents' ]), '</div>'; 
} 
+0

這更加可用,因爲我現在可以輕鬆地使用array_unique()來防止藝術家在一個條目中多次出現。謝謝! – 2012-01-28 12:29:11

0

我想嘗試一個經典switch聲明:

$lastType = ""; 
$count = 0; 

foreach($arrays as $array) { 
    switch($array["type"]) { 
     case "scrobble": 
      if($lastType == "scrobble") 
       $count++; 
      else { 
       $count = 1; 
       $lastType = "scrobble"; 
      } 
      break; 
     case "tweet": 
      // same as above 
      break; 
    } 
} 
0

這做工作:

$last_type = ''; 
$out = array(); 

foreach ($events as $row){ 
    if ($last_type == 'scrobble' && $row['type'] == 'scrobble'){ 
     array_pop($out); 
    } 
    $out[] = $row; 
    $last_type = $row['type']; 
} 

循環執行的每個條目,將它們添加到輸出數組。當我們遇到一個記錄,其中前一個條目也是一個記錄時,從輸出列表中刪除前一個條目。

+0

這其中一個實際上是伎倆。非常感謝! – 2012-01-28 11:05:53

相關問題