2012-09-07 5 views
0

는 I 배열 루프의 현재 위치에서 (요소와 계수 변화없이) 남은 상기 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; 

내가 (다음 생각) 일 것이다 그러나 또한 key이 문자열이 아닌 숫자입니다, 나던.

답변

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

에 사용합니다. 문제 : 당신이 마지막 위치에 있고 다음 키가 없을 때 무엇을해야합니까?

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