2013-04-16 163 views
0

我想将表单中的数据存储到二维数组 ,但它似乎有问题插入数据到数组中。 如果我是为了呼应$ orderArray [0] [$ COUNT2]似乎工作 但如果我是为了呼应$ orderArray [1] [$ COUNT2]会出现错误问题php二维数组

$dateArray = array(); 
$orderArray = array(array()); 
$amountArray = array(array()); 
$count = 0; 
$count2 = 0; 
foreach ($_POST['export'] as $date){ 
    $dateArray[$count] = $date; 
    include "/storescript/connect_to_mysql.php"; 
    $sql = mysql_query("SELECT * FROM ordera WHERE orderDate = '$date' ORDER BY  orderid ASC"); 
    $productCount = mysql_num_rows($sql); // count the output amount 
     if ($productCount > 0) { 
      while($row = mysql_fetch_array($sql)){ 
       $orderArray[$count][$count2] = $row["orderAmount"]; 
       $amountArray[$count][$count2] = $row["itemAmount"]; 
       $count2++; 

      } 
     } 
      $count++; 
    } 
+0

取决于您的数据BU首先,您可以将'$ count ++;'移动到您的if($ productCount> 0){'块,因为如果您的产品数量为0,则不会向您的任何元素添加任何元素数组 – Vytautas

+0

你能更清楚地知道你想要什么吗?顺便说一句,您的输入不安全...... – ibi0tux

+0

您不需要包含连接文件很多次。 – hjpotter92

回答

0

我将减少代码如下:

// connect here 
include "/storescript/connect_to_mysql.php"; 

// make date list safe for querying 
$dates = join(',', array_map(function($date) { 
    return sprintf("'%s'", mysql_real_escape_string($date)); 
}, $_POST['export']); 

// run query  
$sql = "SELECT * FROM ordera WHERE orderDate IN ($dates) ORDER BY orderid"; 
$res = mysql_query($sql) or die("Error in query"); 

// collect results 
while ($row = mysql_fetch_array($res)) { 
    $orders[$date][] = $row['orderAmount']; 
    $amounts[$date][] = $row['itemAmount']; 
} 

// do stuff with results 
foreach ($orders as $date => $orderAmounts) { 
    print_r($orderAmounts); 
    print_r($amounts[$date]); 
} 

另外,请了解PDOmysqli;旧的mysql_函数已弃用。