开发者

Selecting custom indexes in array

I have an nested array that's a mix of words and numbers. It looks like this conceptually. I need to process only numbered indexes such as 15 and 28. I guess this means that I can't use a foreach l开发者_JAVA技巧oop (or is there a way I could). How would you do this?

myarray = (

   someindex = (
     field1 = 
     field2 = 
   );

   15 = (
     field1 = 
     field2 = 
   );

   28 = (
     field1 = 
     field2 = 
   );

   anothertext = (
     field1 = 
     field2 = 
   );

);


foreach($myarr as $key => $item)
{
    if(is_int($key))
    {
        // Do processing here
    }
}

Yes, that will loop through every item in the array, so if you wanted to process the other items separately, you could just add in an else block.


Edit: Changed is_numeric to is_int. See comments for explanation.


You can use foreach

foreach($myarray as $key=>$value)
{
    if(is_int($key))
    {
           //process the entry as you want
    }
}


You could use a FilterIterator with foreach:

class IntKeyFilterIterator extends FilterIterator {
    public function accept() {
        return is_int(parent::key());
    }
}

$it = new IntKeyFilterIterator(new ArrayIterator($array));
foreach ($it as $value) {
    // Will only have those with int keys
}


Another version. Grep the source array for any purely numeric keys, then loop over that result array and do the processing.

$keys = preg_grep('/^\d+$/', array_keys($myarray)) {
foreach($keys as $key) {
    doSomething($myarray[$key]);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜