如果存在循环数组中的下一项

时间:2012-09-07 19:21:47

标签: php arrays next

我想检查是否在数组循环的当前位置内还剩下1个或更多元素(不移动元素并计数):

public function build() {
    $_string = 'CREATE TABLE IF NOT EXISTS `' . dbbuilder::$prefix . $this->name . '` (';
    foreach( $this->rows as $key => $row ) {
        if( $__string = $row->get_string() ) {
            $_string .= $__string . ( next( $this->rows[$key] ) ? ', ' : '' );
        }
    }
    $_string .= ') ENGINE=InnoDB  DEFAULT CHARSET=utf8;';
    $this->string = $_string;
}

输出:

[string:private] => CREATE TABLE IF NOT EXISTS `ecom_accounts` (`id` init(11) NOT NULL  AUTO_INCREMENT`name` varchar(55) NOT NULL `email_address` varchar(255) NOT NULL `password` varchar(32) NOT NULL `multisite` varchar(5) NOT NULL `roll` int(4) NOT NULL DEFAULT '0') ENGINE=InnoDB  DEFAULT CHARSET=utf8;

我认为next()会起作用但它不起作用,key也是一个字符串而不是数字。

3 个答案:

答案 0 :(得分:2)

你可以,例如使用CachingIterator

<?php
$source = array(1,2,3,4,5,6);
$cit = new CachingIterator(new ArrayIterator($source));

foreach($cit as $e) {
    if ( !$cit->hasNext() ) {
        echo 'last element: ';
    }
    echo $e, "\n";
}

打印

1
2
3
4
5
last element: 6

...或者在这种情况下是一个简单的join(', ', $this->rows)

答案 1 :(得分:2)

那个容易的人呢?

$_string = 'CREATE TABLE IF NOT EXISTS `' . dbbuilder::$prefix . $this->name . '` (';
$tmp=array();
foreach( $this->rows as $key => $row )
   if( $__string = $row->get_string() )
      $tmp[]=$__string;
$_string .= implode(',',$tmp);
$_string .= ') ENGINE=InnoDB  DEFAULT CHARSET=utf8;';
$this->string = $_string;

答案 2 :(得分:1)

这可以完成这项工作。唯一的问题:当你在最后一个位置并且没有下一个键时该怎么办?

public function build() {
    $_string = 'CREATE TABLE IF NOT EXISTS `' . dbbuilder::$prefix . $this->name . '` (';
    $keys = array_keys($this->rows);
    $i = 1;
    foreach( $this->rows as $key => $row ) {
        if( $__string = $row->get_string() ) {
            $_string .= $__string . $this->rows[$keys[$i]] ) ? ', ' : '' );
        }
        $i++;
    }
    $_string .= ') ENGINE=InnoDB  DEFAULT CHARSET=utf8;';
    $this->string = $_string;
}