2013-01-16 76 views
3

工作了幾乎整整一天後,我的大腦陷入了我自己關於如何解決這個問題的想法。一個例子。多維數組中的過濾器可能性PHP/Codeigniter

  1. 1,
  2. X,
  3. 2,
  4. 1X,
  5. 1,
  6. 2,
  7. X,
  8. 1,
  9. 2,
  10. 1,
  11. X,
  12. X,
  13. 1 ..

這是一張優惠券,我希望它後組合的可能性進行排序,讓我們說這個優惠券有2個可能的是: 1x2112x121xx1, 1x2x12x121xx1 ..第四場比賽是不同的..

所以......我的問題是這應該怎麼編程。

我從數據庫中獲取數據,它看起來像這樣。

array(
    "gameNumber" => "1", 
    "bets" => array(
     [0] => "1" 
    ), 
    "gameNumber" => "2", 
    "bets" => array(
     [0] = "x" 
    ), 
    "gameNumber" => "3", 
    "bets" => array(
     [0] = "2" 
    ), 
    "gameNumber" => "4", 
    "bets" => array(
     [0] = "1", 
     [1] = "x" 
    ) 
); 

我不確定那會幫助你,但這就是它的樣子。

我已經把它全部放入遞歸數組中,最後回答這個問題的幫助: How to build recursive function to list all combinations of a multi-level array?

所以我的新遞歸函數如下:

public function _combine_bets($array) 
{ 
    $cur = array_shift($array); 
    $result = array(); 

    if(!count($array)) { 
     foreach($cur['bets'] as $option) { 
      $result[] = $cur['matchNumber']."-".$option; 
     } 
     return $result; 
    } 
    foreach($cur['bets'] as $bet) { 
     $result[$cur['matchNumber'].'-'.$bet] = $this->_combine_bets($array); 
    } 
    return $result; 
} 

這樣,我得到這個數組的結果: http://pastie.org/5692408

洙.....回到我的問題,我想使這看起來只是賭注的價值。讓我們說它應該看起來像這樣:1x2112x121xx1,1x2x12x121xx1。而不是一個大陣。我需要爲所有可能性做到這一點,這僅僅是兩種不同的可能性的優惠券,但是..它可以更多。

用戶可以選擇1,X,2,1x,12,上一場比賽我的意思是,這是一個用戶有13個不同遊戲的所有選項x2,1x2,

,如果你需要更多的信息,只是告訴我,我會更新這個..

回答

1

我讓不可能的事情成爲可能,不要問我怎麼做!

function _combine_bets($array, $curBet = null, $currentRow = null) 
{ 
    $cur = array_shift($array); 
    $result = array(); 

    if(!isset($currentRow)) 
     $currentRow = $curBet; 
    else 
     $currentRow .= $curBet; 


    if(!count($array)) { 
     foreach($cur['bets'] as $bet) { 
      $currentRow .= $bet; 
      if(strlen($currentRow) == 13) 
       $this->m_couponRows[] = $currentRow; 
      $currentRow = null; 
     } 
     return $this->m_couponRows; 
    } 

    foreach($cur['bets'] as $bet) { 
     $result[$bet] = $this->_combine_bets($array, $bet, $currentRow); 
    } 
    return $this->m_couponRows; 
} 
1

主要問題是爲什麼你想要一個遞歸函數? 這是一個沒有遞歸的解決方案。

public function _combine_bets($array) { 

    $result = ''; 
    foreach($array['bets'] as $bet) { 
     $result .= $bet; 
    } 
// returns string 
return $result; 
} 

你想要返回什麼?爲什麼你需要遞歸函數?

我不明白這個問題。

+0

我想你是在誤解我的問題。如果我使用你的功能,我會在第四場比賽中獲得1次。這就是它會讓我回來,它會給我每場比賽的賭注。 我希望優惠券行回到我這裏: array( 0 =>'1x2112x121xx1', 1 =>'1x2x12x121xx1' ); – murum

+0

並且您將返回的優惠券是每個matchNumber的投注?如果陣列沒有正確的遊戲編號,那麼投注將被忽略? – Ms01