2013-05-31 106 views
0

我需要在生成的字符串中添加某種匹配計數,但我不知道如何。有沒有辦法給數組添加一些計數?獲取數組中值的數值

我有以下代碼(數據庫查詢的,而之前執行):

while (!$products->EOF) { 
     $purchasedArray[] = array('products_model'=>$products->fields['products_model'], 
           'products_name'=>$products->fields['products_name'], 
           'final_price'=>$products->fields['final_price'], 
           'products_quantity'=>$products->fields['products_quantity']); 
     $products->MoveNext(); 
} 
foreach ($purchasedArray as $purchased) { 
    $formattedProductname[] = $purchased['products_name']; 
    $formattedPrice[] = $purchased['final_price']; 
    $formattedUnits[] = $purchased['products_quantity']; 
} 
$listFinal = implode('|', $formattedProductname); 

現在,這是所有偉大的,工作正常,但我會需要以下的輸出:

product1=cookie|10.00|2&product2=paper|5.00|17&product3=... 

我尋尋覓覓,只是似乎無法找到如何添加計數任何信息(產品* *,產品* * ...) 我應該能(可能)是這個樣子:

foreach ($purchasedArray as $purchased) { 
    $formattedProducts[] = 'product'.**$position** . '=' . $purchased['products_name'] . '|' . $purchased['final_price'] . '|' . $purchased['products_quantity']; 
    $formattedProductname[] = $purchased['products_name']; 
    $formattedPrice[] = $purchased['final_price']; 
    $formattedUnits[] = $purchased['products_quantity']; 
} 

$listFinal = implode('&', $formattedProducts); 
$listFinalProducts = implode('|', $formattedProductname); 

,但我完全不知道如何獲取$position部分...任何幫助將非常感激。

回答

0

您可以通過數組的關鍵做到這一點:

foreach ($purchasedArray as $key=>$purchased) { 
    $formattedProducts[] = 'product'. $key . '=' . $purchased['products_name'] . '|' . $purchased['final_price'] . '|' . $purchased['products_quantity']; 
    $formattedProductname[] = $purchased['products_name']; 
    $formattedPrice[] = $purchased['final_price']; 
    $formattedUnits[] = $purchased['products_quantity']; 
} 

或者你也可以通過添加計數做到這一點:

$count = 0; 
    foreach ($purchasedArray as $purchased) { 
     $count++; 
     $formattedProducts[] = 'product'. $count . '=' . $purchased['products_name'] . '|' . $purchased['final_price'] . '|' . $purchased['products_quantity']; 
     $formattedProductname[] = $purchased['products_name']; 
     $formattedPrice[] = $purchased['final_price']; 
     $formattedUnits[] = $purchased['products_quantity']; 
    } 
0
$idx=1; 
foreach ($purchasedArray as $purchased) { 
    //$formattedProducts[] = 'product'.**$position** . '=' . $purchased['products_name'] . '|' . $purchased['final_price'] . '|' . $purchased['products_quantity']; 
    $formattedProducts[] = 'product'.$idx. '=' . $purchased['products_name'] . '|' . $purchased['final_price'] . '|' . $purchased['products_quantity']; 
    $idx++; 
    $formattedProductname[] = $purchased['products_name']; 
    $formattedPrice[] = $purchased['final_price']; 
    $formattedUnits[] = $purchased['products_quantity']; 
}