【问题标题】:PHP coding problem to get multiple instances from an array based on quantity variable withinPHP编码问题,根据数量变量从数组中获取多个实例
【发布时间】:2009-10-07 10:59:51
【问题描述】:

我不确定是否有人可以帮助我解决我遇到的问题..

我有一个包含代码的解析函数:

foreach ($values as $element) {

$nodeName = $element["tag"];

switch ($element['type']) {

case 'open':

if ($nodeName == "SHOPPINGLIST") {
$this->publicationID = $element["attributes"]["PUBLICATIONID"]; 
}

if ($nodeName == "ENTRY") {

$entry = new ShoppingCartEntry();
$entry->quantity = $element["attributes"]["QUANTITY"];

}

if ($nodeName == "ITEM") {

$entry->productID = $element["attributes"]["PRODUCTID"];
$entry->price = $element["attributes"]["PRICE"];

array_push($this->entries, $entry);
}   

break;

case 'complete':

if ($nodeName == "NAME") {
$entry->name = $element["value"];
}

if ($nodeName == "DESCRIPTION") {
$entry->description = $element["value"];
}   

break;

}
}

因此,我有一个格式如下的数组:

Array ( 
[0] => ShoppingCartEntry Object ( 
[quantity] => 3 
[productID] => 00001 
[price] => 4.99 
[name] => Full English 
[description] => Eggs, Beans, Sheesh Kebab Served with Toast ) 

此刻我正在使用以下方式打印项目条目:

foreach ($entries as $entry) { 
}

但是现在我需要为产品的每个数量值创建一个条目。因此,如果条目中产品的数量是 3,则需要进行更改以创建 3 个条目,或者即使有某种方式可以编辑 foreach 循环,以便它循环“$quantity”数量次..

任何正确方向的指针将不胜感激。

谢谢

【问题讨论】:

    标签: php multidimensional-array


    【解决方案1】:

    像这样?

    foreach ($entries as $entry)
    { 
        for ($i = 0; $i < $entry->quantity; $i++)
        {
            echo $entry->name . ': ' . ($i + 1) . ' of ' . $entry->quantity . '<br>';
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-24
      • 2015-08-30
      • 1970-01-01
      • 2014-09-25
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 2017-04-24
      • 2016-02-12
      相关资源
      最近更新 更多