Skip to content

Instantly share code, notes, and snippets.

@nojimage
Created January 20, 2017 10:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nojimage/2568d4140ffea1b7ccdf89a32ade6475 to your computer and use it in GitHub Desktop.
Save nojimage/2568d4140ffea1b7ccdf89a32ade6475 to your computer and use it in GitHub Desktop.
CakePHP 2.x findEach
<?php
/**
* 検索結果に対して処理を行う
*
* example:
* $model->findEach(['conditions' => ['status' => 1]], function ($data) {
* // $data = ['Model' => [ ... ]]
* debug($data);
* });
*
* @param array $options findオプション
* @param callable $func 適用する処理
* @param integer $window 一度のfindで取得処理する件数
*/
public function findEach(array $options, callable $func, $window = 100)
{
$limit = isset($options['limit']) ? $options['limit'] : 0;
$count = 0;
$options += ['offset' => 0];
$options['limit'] = $window;
while ($results = $this->find('all', $options)) {
$processCount = $count + count($results);
// 全て処理したら limit を超える場合は、対象を切り詰める
if ($limit > 0 && $limit < $processCount) {
$results = array_slice($results, 0, $processCount - $limit);
}
foreach ($results as $result) {
call_user_func($func, $result);
$count++;
}
$options['offset'] += $window;
if ($limit > 0 && $limit <= $count) {
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment