0

I want to check to see if within the current position of an array loop there is a further 1 or more elements left (without shifting the elements and counting):

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;
}

Output:

[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;

I thought next() would work but it doesnt, also the key is a string not number.

4

3 回答 3

2

You can e.g. use the 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";
}

prints

1
2
3
4
5
last element: 6

...or in this case a simple join(', ', $this->rows)

于 2012-09-07T19:26:54.043 回答
2

What about the easy one?

$_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;
于 2012-09-07T19:29:50.077 回答
1

This could do the job. Only problem: what to do when you are at the last position and there is no next key?

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;
}
于 2012-09-07T19:28:41.500 回答