2013-04-25 130 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