php foreach问题

时间:2010-05-06 15:54:18

标签: php cakephp

我有以下代码

$oldID=-1;
$column=0;
foreach($pv->rawData as $data) {
    if ($oldID!= $data->relativeTypeID) {
        $oldID= $data->relativeTypeID;
        $column++;
        $row=1;
    }

    echo "Row: ".$row.": Column: ".$column.": ID".$data->relativeTypeID."<br>"; 

    // if exists a description
    if($data->description) {
        //insert here in the array
        $pv->results[$data->relativeTypeID][$row][0]= $data->relation;
        $pv->results[$data->relativeTypeID][$row][1]= '';
        $pv->results[$data->relativeTypeID][$row][2] ='';
        $pv->results[$data->relativeTypeID][$row][3]  = '';
        $row++;
    }
}

生成此输出:

  

行:1:列:1:ID1
  行:2:列:1:ID1
  行:1:列:2:ID2
  行:2:列:2:ID2
  行:3:列:2:ID2
  行:4:列:2:ID2
  行:5:列:2:ID2
  行:6:列:2:ID2
  行:7:列:2:ID2
  行:8:列:2:ID2
  行:9:列:2:ID2
  行:10:列:2:ID2
  行:11:列:2:ID2
  行:1:列:3:ID3
  行:1:列:4:ID4
  行:1:列:5:ID8
  行:2:列:5:ID8
  行:3:列:5:ID8
  行:1:列:6:ID10
  行:2:列:6:ID10
  行:3:列:6:ID10
  行:4:列:6:ID10
  ...
  ...

我想要它做的是停在前4列,所以我想要一个像这样的输出

  

行:1:列:1:ID1
  行:2:列:1:ID1
  行:1:列:2:ID2
  行:2:列:2:ID2
  行:3:列:2:ID2
  行:4:列:2:ID2
  行:5:列:2:ID2
  行:6:列:2:ID2
  行:7:列:2:ID2
  行:8:列:2:ID2
  行:9:列:2:ID2
  行:10:列:2:ID2
  行:11:列:2:ID2
  行:1:列:3:ID3
  行:1:列:4:ID4

正如你所看到的那样,它停在第4栏。

1 个答案:

答案 0 :(得分:2)

你可以这样做。

foreach($pv->rawData as $data){
  if ($oldID!= $data->relativeTypeID){
    $oldID= $data->relativeTypeID;
    $column++;
    $row=1;
  }
  if ($column >=4) break; // Exit the foreach loop if column is equal to or bigger than 4
  echo "Row: ".$row.": Column: ".$column.": ID".$data->relativeTypeID."

我只是对我的病情偏执,这可能是$ column == 4.你的电话。关键是使用break语句突破循环。如果您愿意,请查看documentation for break here