2012-10-16 37 views
2

好吧,長話短說:我試圖將項目放在一個數組中作爲一個對象的一部分排序(該對象定義爲$ aProductOrdered和公共值:productMan )。該帖子將根據從數據庫添加和刪除的項目而變化,因此它必須是動態的。PHP:二維數組創建索引或添加如果存在

例如,如果指數爲12一定productMan值與所有的項目將在一排像:

[12][0]:prodObj [12][1]:prodObj 
[15][0]:prodObj 
[22][0]:prodObj [22][1]:prodObj 

其中第一是來自物體的prodMan值和第二是任意自動分配的索引循環表示每個對象。

下面是我有,但當我去插入數組,它準確地說我想添加的索引是未定義的。如果索引不存在或者它只是附加到索引,我該如何添加索引?

$vendOrderArray = array(array()); 

//here we will loop through all non blank posted orders and create objects to place them in our $orderArray 
foreach($_POST as $prodID=>$numOrderded) 
{ 
    if(is_numeric($numOrderded) && $numOrderded != "" && $numOrderded != "0") 
    { 
    $aProductOrdered = getProduct($prodId); 
    $aProductOrdered->numberOrdered = $numOrderded; 
    array_push($vendOrderArray[$aProductOrdered->productMan],$aProductOrdered); 
    } 
} 

回答

3
if(!isset($vendOrderArray[$aProductOrdered->productMan])) 
    $vendOrderArray[$aProductOrdered->productMan] = array(); 

就在array_push調用之前。

+0

啊完美的,在被刪除的推薦之後,我做了其他$ vendOrderArray [$ aProductOrdered-> productMan] [0] = $ aProductOrdered;但你的方法更好。謝謝!我不知道爲什麼我沒有考慮使用isset。 – Jeff