2012-03-02 63 views
-1

我正在查詢數據庫,如下所示:現在未定義指數誤差arrya

$result=mysql_query("SELECT name,items FROM mytable WHERE price='$price'"); 

,我想創建一個數組來插入是值這個查詢的結果E'G假設這是得到的數據:

name sellerid quantity 
john  12  10 
joel  23  20 
brian  40  10 

i.ve插入這個數據到一個數組,需要處理它(這是一個交易平臺),讓我們說,用戶想購買從數據25項。該數組,所以爲了達到這個目的,腳本必須從joel中取​​10個john項和15個joel項(加起來爲25),然後設置t繼承物品的剩餘價值,即約翰的物品= 0和喬爾的物品= 5。

這是code.i我在這條線得到一個錯誤約未定義指數

$assignedQuantityPerUser[ $row[ "sellerid" ] ] += $totalUnitsOrdered; 

這是代碼的其餘部分:

$query="SELECT itemquantity,sellerid FROM mytable WHERE price='$price'";      
//it is a table containing data about people selling their commoditities and the   program matches buyers and sellers by price 
$foundItems = array(); 

// likely to be a parameter of a function... 
$totalUnitsOrdered = 25; 

// maps user to amount assigned from him 
$assignedQuantityPerUser = array(); 


while ($row = mysql_fetch_assoc($cursor)) { 

// Still order Quantity left? 
if (0 < $totalUnitsOrdered) { 

    if ($row[ "itemquantity" ] <= $totalUnitsOrdered) { 

// assign all of $row[ "items" ] 
$totalUnitsOrdered       -= 0 + $row[ "itemquantity" ]; 
    $assignedQuantityPerUser[ $row[ "sellerid" ] ] += 0 + $row[ "itemquantity" ]; 
**//this is where in getting an error:r[ $row[ "sellerid" ] is an undefined index** 
} else { 

    // assign all the rest: $totalUnitsOrdered 
    $totalUnitsOrdered       = 0; 
    $assignedQuantityPerUser[ $row[ "sellerid" ] ] += $totalUnitsOrdered; 

} 

} 


$newItem[] = $row[ "sellerid" ]; 
$newItem[] = $row[ "itemquantity" ]; 

// Append $newItem to the end of $foundItems 
$foundItems[] = $newItem; 

} // while 

親切assist.thanks。

回答

3

初始化值使用它之前:

if (!isset($assignedQuantityPerUser[$row["sellerid"]])) { 
    $assignedQuantityPerUser[$row["sellerid"]] = 0; 
} 
$assignedQuantityPerUser[$row["sellerid"]] += $totalUnitsOrdered; 
+0

但「sellerid」是從數據庫中檢索(如可以從上面的表中看到)值,因此不應該初始化爲不同的值。 。我怎麼解決這個問題?..我不確定代碼是否正確。 – che 2012-03-02 11:21:39

+0

您正在使用sellerid作爲KEY來解決數組中的元素。該元素需要初始化。這樣做並不會改變sellerid本身。 – rodneyrehm 2012-03-02 11:23:45

+0

感謝它的工作。問題是,現在的代碼只是循環遍歷值而不更新它們在數據庫中,我怎麼能更新每個在DB.how受影響的值我可以更新每個值array.thanks許多。 – che 2012-03-04 14:16:30