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=...

我正在搜索和搜索,但似乎找不到任何有关如何添加该计数的信息(产品* 1 *,产品* 2 *...)我应该(可能)看起来像这样:

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部分......任何帮助将不胜感激。

4

2 回答 2

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'];
}
于 2013-05-31T03:38:12.830 回答
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'];
    }
于 2013-05-31T03:36:39.263 回答