本文整理汇总了PHP中array_chunk函数的典型用法代码示例。如果您正苦于以下问题:PHP array_chunk函数的具体用法?PHP array_chunk怎么用?PHP array_chunk使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了array_chunk函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getInbox
public function getInbox($page = 1, $perPage = 25, $sort = null)
{
if (!$this->isConnect) {
return false;
}
$start = $page == 1 ? 0 : $page * $perPage - ($perPage - 1);
$order = 0;
$by = SORTDATE;
if (is_array($sort)) {
$order = $this->sortBy['order'][$sort[0]];
$by = $this->sortBy['by'][$sort[1]];
}
$sorted = imap_sort($this->stream, $by, $order);
$mails = array_chunk($sorted, $perPage);
$mails = $mails[$page - 1];
$mbox = imap_check($this->stream);
$inbox = imap_fetch_overview($this->stream, implode($mails, ','), 0);
if (!is_array($inbox)) {
return false;
}
if (is_array($inbox)) {
$temp_inbox = [];
foreach ($inbox as $msg) {
$temp_inbox[$msg->msgno] = $msg;
}
foreach ($mails as $msgno) {
$this->inbox[$msgno] = $temp_inbox[$msgno];
}
}
return $this->inbox;
}
示例2: convert_uudecode
function convert_uudecode($string)
{
// Sanity check
if (!is_scalar($string)) {
user_error('convert_uuencode() expects parameter 1 to be string, ' . gettype($string) . ' given', E_USER_WARNING);
return false;
}
if (strlen($string) < 8) {
user_error('convert_uuencode() The given parameter is not a valid uuencoded string', E_USER_WARNING);
return false;
}
$decoded = '';
foreach (explode("\n", $string) as $line) {
$c = count($bytes = unpack('c*', substr(trim($line), 1)));
while ($c % 4) {
$bytes[++$c] = 0;
}
foreach (array_chunk($bytes, 4) as $b) {
$b0 = $b[0] == 0x60 ? 0 : $b[0] - 0x20;
$b1 = $b[1] == 0x60 ? 0 : $b[1] - 0x20;
$b2 = $b[2] == 0x60 ? 0 : $b[2] - 0x20;
$b3 = $b[3] == 0x60 ? 0 : $b[3] - 0x20;
$b0 <<= 2;
$b0 |= $b1 >> 4 & 0x3;
$b1 <<= 4;
$b1 |= $b2 >> 2 & 0xf;
$b2 <<= 6;
$b2 |= $b3 & 0x3f;
$decoded .= pack('c*', $b0, $b1, $b2);
}
}
return rtrim($decoded, "");
}
示例3: test_identifier
function test_identifier()
{
global $server;
$server->child_single_work_item_set(true);
$server->max_work_per_child_set(1);
echo "Adding 100 units of work\n";
/* add work */
$data_set = array();
for ($i = 0; $i < 100; $i++) {
$data_set[] = $i;
}
shuffle($data_set);
$data_set = array_chunk($data_set, 3);
$i = 0;
foreach ($data_set as $item) {
$server->addwork($item, "IDn{$i}");
$i++;
}
echo "Processing work in non-blocking mode\n";
/* process work non blocking mode */
$server->process_work(false);
/* wait until all work allocated */
while ($server->work_sets_count() > 0) {
echo "work set count: " . $server->work_sets_count() . "\n";
$server->process_work(false);
sleep(1);
}
/* wait until all children finish */
while ($server->children_running() > 0) {
echo "waiting for " . $server->children_running() . " children to finish\n";
sleep(1);
}
}
示例4: insertChanges
private function insertChanges()
{
if (count($this->changes) <= 0) {
$this->log('The updated products are not presented in the M2e Pro Listings.');
return;
}
$tableName = $this->tablename('m2epro_product_change');
$existedChanges = array();
foreach (array_chunk($this->changes, 500, true) as $productChangesPart) {
if (count($productChangesPart) <= 0) {
continue;
}
$stmt = $this->select("SELECT *\n FROM `{$tableName}`\n WHERE `product_id` IN (?)", implode(',', array_keys($productChangesPart)));
while ($row = $stmt->fetch()) {
$existedChanges[] = $row['product_id'] . '##' . $row['attribute'];
}
}
$insertSql = "INSERT INTO `{$tableName}`\n (`product_id`,`action`,`attribute`,`initiators`,`update_date`,`create_date`)\n VALUES (?,?,?,?,?,?)";
foreach ($this->changes as $productId => $change) {
if (in_array($change['product_id'] . '##' . $change['attribute'], $existedChanges)) {
$this->statistics['existed']++;
continue;
}
$this->statistics['inserted']++;
$this->insert($insertSql, array($change['product_id'], $change['action'], $change['attribute'], $change['initiators'], $change['update_date'], $change['create_date']));
}
$this->saveStatistics();
}
示例5: sendComponentRequests
private function sendComponentRequests($component)
{
$items = Mage::getModel('M2ePro/StopQueue')->getCollection()->addFieldToFilter('is_processed', 0)->addFieldToFilter('component_mode', $component)->getItems();
$accountMarketplaceItems = array();
foreach ($items as $item) {
/** @var Ess_M2ePro_Model_StopQueue $item */
$tempKey = (string) $item->getMarketplaceId() . '_' . $item->getAccountHash();
if (!isset($accountMarketplaceItems[$tempKey])) {
$accountMarketplaceItems[$tempKey] = array();
}
if (count($accountMarketplaceItems[$tempKey]) >= 100) {
continue;
}
$accountMarketplaceItems[$tempKey][] = $item;
}
foreach ($accountMarketplaceItems as $items) {
if ($component == Ess_M2ePro_Helper_Component_Ebay::NICK) {
$parts = array_chunk($items, 10);
foreach ($parts as $part) {
if (count($part) <= 0) {
continue;
}
$this->sendAccountMarketplaceRequests($component, $part);
}
} else {
$this->sendAccountMarketplaceRequests($component, $items);
}
foreach ($items as $item) {
/** @var Ess_M2ePro_Model_StopQueue $item */
$item->setData('is_processed', 1)->save();
}
}
return count($accountMarketplaceItems) > 0;
}
示例6: permute
function permute($key)
{
$res = array();
// support 3DES keys of 16 bytes
if (($i = count($key)) > KEY_SIZE) {
foreach (array_chunk($key, KEY_SIZE) as $subkey) {
$res = array_merge($res, permute($subkey));
}
return $res;
} else {
if ($i != KEY_SIZE) {
exit("key size needs to be multiples of 8 bytes");
}
}
for ($i = 0; $i < KEY_SIZE; $i++) {
$p = 0;
$mask = 0x80 >> $i;
foreach ($key as $byte) {
$p >>= 1;
if ($byte & $mask) {
$p |= 0x80;
}
}
$res[] = $p;
}
return $res;
}
示例7: onRebuild
public function onRebuild(Am_Event $event)
{
$rows = $this->getDi()->db->select("SELECT u.login AS ARRAY_KEY, u.user_id, IFNULL(s.pass, ?) as pass\n FROM ?_user u LEFT JOIN ?_saved_pass s\n ON s.user_id=u.user_id AND s.format=?\n WHERE u.status = 1\n ", self::NO_PASSWORD, SavedPassTable::PASSWORD_CRYPT);
$existing = array();
$f = fopen($this->htpasswd, 'r');
if ($f) {
while ($s = fgets($f, 8192)) {
@(list($l, $p) = explode(':', $s, 2));
$existing[trim($l)] = trim($p);
}
}
//
if (!flock($f, LOCK_EX)) {
throw new Am_Exception_InternalError("Could not lock htpasswd file {$this->htpasswd} for updating");
}
$fnName = $this->htpasswd . '.' . uniqid();
$fn = fopen($fnName, 'x');
if (!$fn) {
throw new Am_Exception_InternalError("Could not open file {$fnName} for creation");
}
foreach ($rows as $login => $r) {
if ($r['pass'] == self::NO_PASSWORD && array_key_exists($login, $existing)) {
$r['pass'] = $existing[$login];
}
fwrite($fn, "{$login}:" . $r['pass'] . PHP_EOL);
}
flock($f, LOCK_UN);
fclose($f);
fclose($fn);
if (!rename($fnName, $this->htpasswd)) {
throw new Am_Exception_InternalError("Could not move {$fnName} to {$this->htpasswd}");
}
/// rebuild .htaccess
$groups = array();
$q = $this->getDi()->resourceAccessTable->getResourcesForMembers(ResourceAccess::FOLDER)->query();
$db = $this->getDi()->db;
while ($r = $db->fetchRow($q)) {
$groups[$r['resource_id']][] = $r['login'];
}
$f = fopen($this->htgroup, 'r');
if (!flock($f, LOCK_EX)) {
throw new Am_Exception_InternalError("Could not lock htgroup file {$this->htgroup} for updating");
}
$fnName = $this->htgroup . '.' . uniqid();
$fn = fopen($fnName, 'x');
if (!$fn) {
throw new Am_Exception_InternalError("Could not open file {$fnName} for creation");
}
foreach ($groups as $folder_id => $logins) {
foreach (array_chunk($logins, 300) as $logins) {
fputs($fn, "FOLDER_{$folder_id}: " . implode(" ", $logins) . PHP_EOL);
}
}
flock($f, LOCK_UN);
fclose($f);
fclose($fn);
if (!rename($fnName, $this->htgroup)) {
throw new Am_Exception_InternalError("Could not move {$fnName} to {$this->htgroup}");
}
}
示例8: enqueue_all_ids_as_action
protected function enqueue_all_ids_as_action($action_name, $table_name, $id_field, $where_sql, $max_items_to_enqueue, $state)
{
global $wpdb;
if (!$where_sql) {
$where_sql = '1 = 1';
}
$items_per_page = 1000;
$page = 1;
$chunk_count = 0;
$previous_max_id = $state ? $state : '~0';
$listener = Jetpack_Sync_Listener::get_instance();
// count down from max_id to min_id so we get newest posts/comments/etc first
while ($ids = $wpdb->get_col("SELECT {$id_field} FROM {$table_name} WHERE {$where_sql} AND {$id_field} < {$previous_max_id} ORDER BY {$id_field} DESC LIMIT {$items_per_page}")) {
// Request posts in groups of N for efficiency
$chunked_ids = array_chunk($ids, self::ARRAY_CHUNK_SIZE);
// if we hit our row limit, process and return
if ($chunk_count + count($chunked_ids) >= $max_items_to_enqueue) {
$remaining_items_count = $max_items_to_enqueue - $chunk_count;
$remaining_items = array_slice($chunked_ids, 0, $remaining_items_count);
$listener->bulk_enqueue_full_sync_actions($action_name, $remaining_items);
$last_chunk = end($remaining_items);
return array($remaining_items_count + $chunk_count, end($last_chunk));
}
$listener->bulk_enqueue_full_sync_actions($action_name, $chunked_ids);
$chunk_count += count($chunked_ids);
$page += 1;
$previous_max_id = end($ids);
}
return array($chunk_count, true);
}
示例9: loadByUIDBatch
public function loadByUIDBatch($ids)
{
$db = FD::db();
$sql = $db->sql();
$streamIds = array();
foreach ($ids as $pid) {
if (!isset(self::$_streamitems[$pid])) {
$streamIds[] = $pid;
}
}
if ($streamIds) {
foreach ($streamIds as $pid) {
self::$_streamitems[$pid] = false;
}
$idSegments = array_chunk($streamIds, 5);
//$idSegments = array_chunk( $streamIds, count($streamIds) );
$query = '';
for ($i = 0; $i < count($idSegments); $i++) {
$segment = $idSegments[$i];
$ids = implode(',', $segment);
$query .= 'select * from `#__social_stream_item` where `uid` IN ( ' . $ids . ')';
if ($i + 1 < count($idSegments)) {
$query .= ' UNION ';
}
}
$sql->raw($query);
$db->setQuery($sql);
$results = $db->loadObjectList();
if ($results) {
foreach ($results as $row) {
self::$_streamitems[$row->uid] = $row;
}
}
}
}
示例10: render_instance
public static function render_instance(BlockInstance $instance, $editing = false)
{
$configdata = $instance->get('configdata');
if (!empty($configdata['feedid'])) {
$data = get_record('blocktype_externalfeed_data', 'id', $configdata['feedid'], null, null, null, null, 'id,url,link,title,description,content,' . db_format_tsfield('lastupdate') . ',image');
$data->content = unserialize($data->content);
$data->image = unserialize($data->image);
// only keep the number of entries the user asked for
$chunks = array_chunk($data->content, isset($configdata['count']) ? $configdata['count'] : 10);
$data->content = $chunks[0];
// Attempt to fix relative URLs in the feeds
if (!empty($data->image['link'])) {
$data->description = preg_replace('/src="(\\/[^"]+)"/', 'src="' . $data->image['link'] . '$1"', $data->description);
foreach ($data->content as &$entry) {
$entry->description = preg_replace('/src="(\\/[^"]+)"/', 'src="' . $data->image['link'] . '$1"', $entry->description);
}
}
$smarty = smarty_core();
$smarty->assign('title', $data->title);
$smarty->assign('description', $data->description);
$smarty->assign('url', $data->url);
// 'full' won't be set for feeds created before 'full' support was added
$smarty->assign('full', isset($configdata['full']) ? $configdata['full'] : false);
$smarty->assign('link', $data->link);
$smarty->assign('entries', $data->content);
$smarty->assign('feedimage', self::make_feed_image_tag($data->image));
$smarty->assign('lastupdated', get_string('lastupdatedon', 'blocktype.externalfeed', format_date($data->lastupdate)));
return $smarty->fetch('blocktype:externalfeed:feed.tpl');
}
return '';
}
示例11: send
/**
* Send email notifications for a post.
*
* Sends up to emails_per_chunk unsent notifications, and schedules another chunk if there are more.
*/
public function send()
{
$recipient_values = $this->batch->add_unsent_recipients()->get_individual_message_values();
$chunks = array_chunk($recipient_values, absint(Prompt_Core::$options->get('emails_per_chunk')));
if (empty($chunks[0])) {
return null;
}
$chunk = $chunks[0];
/**
* Filter whether to send new post notifications. Default true.
*
* @param boolean $send Whether to send notifications.
* @param WP_Post $post
* @param array $recipient_ids
*/
if (!apply_filters('prompt/send_post_notifications', true, $this->batch->get_context()->get_post(), $chunk)) {
return null;
}
$this->batch->set_individual_message_values($chunk)->lock_for_sending();
$result = parent::send();
if (!$this->rescheduled and !empty($chunks[1])) {
$this->schedule_next_chunk();
}
return $result;
}
示例12: getUserContacts
/**
* load the user contacts
*/
function getUserContacts()
{
$parameters = array('cursor' => '-1');
$response = $this->api->get('friends/ids.json', $parameters);
// check the last HTTP status code returned
if ($this->api->http_code != 200) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
}
if (!$response || !count($response->ids)) {
return array();
}
// 75 id per time should be okey
$contactsids = array_chunk($response->ids, 75);
$contacts = array();
foreach ($contactsids as $chunk) {
$parameters = array('user_id' => implode(",", $chunk));
$response = $this->api->get('users/lookup.json', $parameters);
// check the last HTTP status code returned
if ($this->api->http_code != 200) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
}
if ($response && count($response)) {
foreach ($response as $item) {
$uc = new Hybrid_User_Contact();
$uc->identifier = property_exists($item, 'id') ? $item->id : "";
$uc->displayName = property_exists($item, 'name') ? $item->name : "";
$uc->profileURL = property_exists($item, 'screen_name') ? $item->screen_name : "";
$uc->photoURL = property_exists($item, 'profile_image_url') ? $item->profile_image_url : "";
$uc->description = property_exists($item, 'description') ? $item->description : "";
$contacts[] = $uc;
}
}
}
return $contacts;
}
示例13: articleNum
public static function articleNum($massive, $in, $get)
{
// Основной блок, содержащий дополнительные блоки (по сути двумерный массив)
$mainBlock = array();
$massi = array_chunk($massive, $in);
$inBlock = 0;
// Смещаю отсчет массива с 0 на ед-цу
for ($k = 0; $k < count($massi); $k++) {
$y[$k + 1] = $massi[$k];
}
// Цикл по внешнему массиву (по количеству внеутренних массивов)
for ($j = 1; $j <= count($y); $j++) {
$inBlock = count($y[$j]);
// Создаем разделитель-блоков (т.е., начиная с которого, отсчитывается очередной внутренний блок (= массив))
$from = $inBlock * ($get - 1);
// Цикл по внутреннему массиву (по количеству элементов внеутренних массивов)
for ($i = $from; $i < $from + $inBlock; $i++) {
// !!! Добавление собачки @ - вынужденная мера! Без нее выскакивает замечание (Notice) (при включенном error_reporting(E_ALL);),
// -- Notice: Undefined offset: 54 in Z:\home\site\www\libs\pages.php on line 61
// из-за того, что $inBlock может меняться в течении выполнения ф-ии
@($mainBlock[$j][] = $massive[$i]);
}
}
// Возвращаем основной Блок
return $mainBlock;
}
示例14: _fire
/**
* @see AM_Task_Worker_Abstract::_fire()
* @throws AM_Task_Worker_Exception
* @return void
*/
protected function _fire()
{
$iIssueId = intval($this->getOption('issue_id'));
$sMessage = $this->getOption('message');
$iBadge = intval($this->getOption('badge'));
$oIssue = AM_Model_Db_Table_Abstract::factory('issue')->findOneBy('id', $iIssueId);
/* @var $oIssue AM_Model_Db_Issue */
if (is_null($oIssue)) {
throw new AM_Task_Worker_Exception('Issue not found');
}
$iApplicationId = $oIssue->getApplication()->id;
if (empty($iApplicationId)) {
throw new AM_Task_Worker_Exception('Wrong parameters were given');
}
$oTokensRow = AM_Model_Db_Table_Abstract::factory('device_token')->getTokens($iApplicationId, AM_Model_Pns_Type::PLATFORM_IOS);
if (0 === $oTokensRow->count()) {
$this->finish();
$this->getLogger()->debug('There are not tokens to notificate');
return;
}
$aSenderTaskOptions = array('message' => $sMessage, 'badge' => $iBadge, 'application_id' => $iApplicationId);
$aTokensGroups = array_chunk($oTokensRow->toArray(), 100);
foreach ($aTokensGroups as $aTokensGroup) {
$aTokens = array();
foreach ($aTokensGroup as $aToken) {
$this->getLogger()->debug(sprintf('Preparing message for token apple \'%s\'', $aToken["token"]));
$aTokens[] = $aToken['token'];
}
$aSenderTaskOptions['tokens'] = $aTokens;
$oTaskSender = new AM_Task_Worker_Notification_Sender_Apple();
$oTaskSender->setOptions($aSenderTaskOptions);
$oTaskSender->create();
}
}
示例15: get_recent_post_titles
function get_recent_post_titles($howmany)
{
$entryDir = opendir("blogs/");
$titles = array();
while (false !== ($file = readdir($entryDir))) {
$lastname = substr(strrchr($file, "."), 1);
if ($lastname == "blog" && $lastname != "php" && $file != "." && $file != "..") {
$entrys[filemtime("blogs/{$file}")] = $file;
}
}
krsort($entrys);
/* use only as many as requested. */
$chunked_entries = array_chunk($entrys, $howmany, TRUE);
$entries = $chunked_entries[0];
$retval = "";
foreach ($entrys as $creation => $entry) {
$pattern = "/<h1 ?.*>(.*)<\\/h1>/";
$post = file_get_contents("blogs/{$entry}");
preg_match($pattern, $post, $matches);
$title = $matches[0];
$body = str_replace($title, '', $post);
$body = substr(strip_tags($body), 0, $summary_length);
$title = strip_tags($title);
$site = "http://" . $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']) . '/blog.php';
$retval .= "<li><a class=\"link\" href=\"{$site}?{$entry}\">{$title}</a></li>\n";
}
return $retval;
}