PHP 发出错误未定义的偏移错误


PHP issues the error undefined offset error

我想比较两个MySQL表,如果不在table 1中,则删除table 2列。我使用的代码是

<?php 
mysql_connect("localhost", "root", "") or die(mysql_error()); 
mysql_select_db("test") or die(mysql_error()); 

$fields = array();
$fields2 = array();
$dropcols = array();
$res=mysql_query("SHOW COLUMNS FROM table1");
$res2=mysql_query("SHOW COLUMNS FROM table2");
while ($x = mysql_fetch_assoc($res)) {
    $fields[] = $x['Field'];
}
while ($x = mysql_fetch_assoc($res2)) {
    $fields2[] = $x['Field'];
}
$diff = array_diff($fields2,$fields);
$arraylen = count($diff);
for ($x=0; $x < $arraylen; $x++) {
    mysql_query("ALTER TABLE table2   DROP  $diff[$x]");
}
有时

代码工作,有时发出错误未定义的偏移量0。我不知道错误在哪里。

array_diff不会重新索引结果数组的元素,它们会阻止索引fields,因此索引中存在间隙。使用 foreach 遍历数组值,而不考虑索引。

foreach ($diff as $column) {
    mysql_query(  "ALTER TABLE table2   DROP  $column");
}

或者你可以做:

$diff = array_values(array_diff($fields2, $fields));
有时数组

$diff不包含任何值