2013-04-25 74 views
0

我在這裏有一個獨特的情況,我不確定這是否是正確的方式去做;我樂於接受建議。在foreach循環中創建數組的一個實例

我有一個函數,它抓取數據庫中的所有表名並將它們存儲到數組中。接下來新分析的項目($ id)針對此表名稱數組傳遞,並且未從此數組中設置任何匹配項。這留下了剩餘物品,這些物品已經停產。下面

代碼:

function itemDiscontinued($dbh, $id, $detail) { 
    try { 
     $tableList = array(); 
     $result = $dbh->query("SHOW TABLES"); 
     while ($row = $result->fetch()) { 
      $tableList[] = $row[0]; 
     } 
     $key = array_search($id, $tableList); 
     unset($tableList[$key]); 
     print_r($tableList); 
     } 
    catch (PDOException $e) { 
     echo $e->getMessage(); 
    } 
} 

的問題是,數組$ tablelist保持重建本身由於該函數在foreach循環(解析過程)之中。一旦創建它,​​我只需要一個它的實例。如果問題有點難以理解,我很抱歉。

+0

只需事先創建,並通過'$ tablelist'到功能的array_push? – silkfire 2013-04-25 21:59:44

回答

1

是的,這真的很難理解。也許你會嘗試這個辦法:

function itemDiscontinued($dbh, $id, $detail) { 
    static $tables = array(); 
    if (!$tables) { 
     $tables = getTableList($dbh); 
    } 
    $key = array_search($id, $tables); 
    unset($tables[$key]); 
    print_r($tables); 
} 

function getTableList($dbh) { 
    try { 
     $tableList = array(); 
     $result = $dbh->query("SHOW TABLES"); 
     while ($row = $result->fetch()) { 
      $tableList[] = $row[0]; 
     } 
     return $tableList; 
    } catch (PDOException $e) { 
     echo $e->getMessage(); 
    } 
} 
+0

這就是我所得到的結果,即使是你提出的改變。 '338142:表已存在 - >沒有價格變化found2Array([0] => 113340 [1] => 116516 [3] => 20731 [4] => 25500 [5] => 322320 [6] => 322459 [7] => 323003 [8] => 325958 [9] => 325961 [10] => 325963 [11] => 326002 [12] => 326035)' '139431:表已存在 - >沒有價格change found3Array([0] => 113340 [1] => 116516 [2] => 139431 => 20731 [4] => 25500 [5] => 322320 [6] => 322459 [7] => 323003 [8 ] => 325958 [9] => 325961 [10] => 325963 [11] => 326002 [12] => 326035)請注意數組前的數字是$鍵:) – DrDog 2013-04-25 22:19:27

+0

謝謝picios!這完全符合我希望的方式。它將陣列耗盡到物品左側。 :) – DrDog 2013-04-25 23:32:12

1

怎麼樣用一個額外的參數

function itemDiscontinued($dbh, $id, $detail, $outputArray) { 
    try { 
     $result = $dbh->query("SHOW TABLES"); 
     while ($row = $result->fetch()) { 
      array_push($outputArray, $row[0]); 
     } 
     $key = array_search($id, $outputArray); 
     unset($outputArray[$key]); 
     return $outputArray; // use this for subsequent run on the foreach statment 
     } 
    catch (PDOException $e) { 
     echo $e->getMessage(); 
    } 
} 
+1

感謝丹的努力,但上面的代碼是爲我工作的解決方案。 – DrDog 2013-04-25 23:32:44

相關問題