开发者

PHP foreach on array of objects AND single object?

I have a rather big php script that uses the foreach loop pretty often. The wa开发者_如何学Goy it works now is I pass an array of objects to every foreach loop, but I want to modify the script to work with just an object also. I would really hate and don't think it's reasonable to check before each loop if it's an array of objects or just a single object and depending on the situation to loop through the array or just do stuff with the single object. Any workaround this? Thanks in advance


$item = $obj;
// or
$item = array( ... );

if(!is_array($item))
   $item = array($item);

foreach($item as $individual)
{
   //...
}


You can pass an array with a single object inside it. Or use a polymorphic constructor/function setup.

Passing an array with a single object is pretty obvious how to do it, here's some other possible ways to deal with it:

function test($var)
{
     if(is_a($var,"ClassName")) //Test to see if the passed variable is a member of the class and not an array and put it in an array if so
     {
          $var = array($var);
     }

     foreach($var as $v)
     {
          //Do stuff
     }
}

function test($var)
{
    if(is_array($var)) //Test if object is array or class, call different functions depending on which it is
    {
        call_user_func_array(array($this,'doArray'),$var);
    }
    elseif(is_a($var,"Classname"))
    {
        call_user_func_array(array($this,'doObject'),$var);
    }
}


Sounds like you need to write a function/Would this serve your purposes?

if(is_array($thingy)){
    foreach($thingy as $thing){
        function($thing);
    }
}else{
    function($thingy);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜