开发者

Reducing Foreach loops?

It put the data into $itemsData[] array from modelItem::find() loop

When I outputing the data, I have to do foreach twice, how to reduce into 1 foreach loop?

$itemsData = array();
foreach ($_SESSION['Cart'] as $optionid => $OptionData) {
    $item = modelItem::find('id = :item_id', array('item_id' => $OptionData['item_id']));
    $itemsData[] = $item;
}


// How to put this in into single foreach?
foreach ($itemsData as $items) {
     foreach($items as $item) {
         echo $item->name;
     }
 }



Array
(
    [0] => Array
        (
            [0] => modelItem Object
                (
                    [id] => 319
                    [name] => xxxxxx xxxxxx
                    [category_id] => 434
                )

        )

    [1] => Array
        (
            [0] => modelItem Object
                (
                    [id] => 320
                    [name] => xxx & xxxx xxxxx
                    [category_id] => 424
      开发者_如何学编程          )

        )

)


The reason you need to use foreach twice, is because mysql itself, returns a set. "modelItem::find" returns an array in turn.

When you do $itemsData[] = $item; you append an array. Resulting in a nested array.

A simple solution would be to change:

$item = modelItem::find('id = :item_id', array('item_id' => $OptionData['item_id']));
foreach($item as $x)
    $itemsData[] = $x;

But this still gives you a foreach, so you might wanna try:

$item = modelItem::find('id = :item_id', array('item_id' => $OptionData['item_id']));
$itemsData=array_merge($itemsData, $item);

In this second example you can even pass modelItem::find() directly.


right code is

foreach ($_SESSION['Cart'] as $optionid => $OptionData) {
   $item = modelItem::find('id = :item_id', array('item_id' => $OptionData['item_id']));
   if(!empty($item)){
     $item = array_shift($item);
     echo $item->name;
   }
}

What it basically does is, assumes that the $item array has only one element and uses this element via shift as the element to echo. It is allways good to know PHP's array functions by heart. Take a look at

http://php.net/manual/de/ref.array.php

See working code

http://codepad.org/lyDlutFm

for an example

Regards


Seems to me you can already do one loop:

foreach ($itemsData as $item) {
     echo $item->name;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜