本文整理汇总了PHP中array_reduce函数的典型用法代码示例。如果您正苦于以下问题:PHP array_reduce函数的具体用法?PHP array_reduce怎么用?PHP array_reduce使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了array_reduce函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getSumPrice
/**
* @param integer $object_model_id
* @param string $type
* @return string
*/
public static function getSumPrice($object_model_id, $type)
{
$objects = static::find()->select('price')->where(['special_price_list_id' => ArrayHelper::map(SpecialPriceList::getModelsByKey($type), 'id', 'id'), 'object_model_id' => $object_model_id])->asArray()->all();
return array_reduce($objects, function ($result, $item) {
return $result += $item['price'];
}, 0);
}
示例2: buildResponse
/**
* @return Response
* @throws \RuntimeException
*/
public function buildResponse()
{
if (!$this->isComplete) {
throw new \RuntimeException('Response not complete yet');
}
return array_reduce($this->records, function (Response $response, Record $record) {
switch ($record->type) {
case Record::BEGIN_REQUEST:
case Record::ABORT_REQUEST:
case Record::PARAMS:
case Record::STDIN:
case Record::DATA:
case Record::GET_VALUES:
throw new \RuntimeException('Cannot build a response from an request record');
break;
case Record::STDOUT:
$response->content .= $record->content;
break;
case Record::STDERR:
$response->error .= $record->content;
break;
case Record::END_REQUEST:
break;
case Record::GET_VALUES_RESULT:
break;
case Record::UNKNOWN_TYPE:
break;
default:
throw new \RuntimeException('Unknown package type received');
break;
}
return $response;
}, new Response());
}
示例3: serve
public function serve($cycle = null, $flags = 0)
{
$cycle = $cycle ? $cycle : Cycle::create();
$result = $this->dispatch($cycle->request()->getMethod(), $cycle->request()->getUri()->getPath(), $flags);
if (!$result) {
$w = $cycle(404, []);
$w($cycle->request()->getUri());
return $this->emit($cycle);
}
$plugins = $result['plugins'];
$cycle->setMountPoint($result['mountpoint']);
$cycle->setPathParameters($result['parameters']);
$runner = $result['handler'];
if (!is_callable($runner)) {
//build method annotation plugins
$plugins = array_merge($runner->buildPlugins($result['annotationPlugins'] + $this->getAnnotationPlugins()), $plugins);
$runner = $runner->getCallable();
}
//build callable
$callable = array_reduce(array_merge($plugins, $this->plugins), function ($carry, $item) {
return $item($carry);
}, $runner);
$r = $callable($cycle);
return $this->emit($cycle, $r);
}
示例4: load
public function load($indexList = null, $column = false)
{
$sqlQuery = new SqlQuery();
$column = $column ? $column : $this->index;
if (isset($indexList)) {
$indexList = " WHERE " . $column . " IN (" . implode(',', $indexList) . ")" . implode(' AND ', $this->filters);
} else {
$indexList = array_reduce($this->filters, function ($prev, $next) {
return $prev == "" ? " WHERE " . $next : $prev . " AND " . $next;
}, "");
}
if ($this->order) {
$indexList .= ' ORDER BY `' . $this->orderColumn . '` ' . $this->orderDir;
}
if ($this->limit > -1) {
$indexList .= ' LIMIT ' . $this->limit;
}
$sql = "SELECT * FROM " . $this->table . $indexList;
$result = $sqlQuery->execute($sql);
if ($result['status']) {
foreach ($result['data'] as $item) {
$this->processItem($item);
}
}
}
示例5: handleBatch
/**
* {@inheritdoc}
*/
public function handleBatch(array $records)
{
$level = $this->level;
// filter records based on their level
$records = array_filter($records, function ($record) use($level) {
return $record['level'] >= $level;
});
if (!$records) {
return;
}
// the record with the highest severity is the "main" one
$record = array_reduce($records, function ($highest, $record) {
if ($record['level'] >= $highest['level']) {
return $record;
}
return $highest;
});
// the other ones are added as a context item
$logs = array();
foreach ($records as $r) {
$logs[] = $this->processRecord($r);
}
if ($logs) {
$record['context']['logs'] = (string) $this->getBatchFormatter()->formatBatch($logs);
}
$this->handle($record);
}
示例6: execute
/**
* @inheritdoc
*/
public function execute()
{
$pipes = array_reverse($this->pipes);
/** @type \Closure $linked_closure */
$linked_closure = array_reduce($pipes, $this->getIterator(), $this->getInitial($this->thenClosure));
return $linked_closure(...$this->parameters);
}
示例7: getOneById
/**
* Get loaded shipping method given its id
*
* @param CartInterface $cart Cart
* @param string $shippingMethodId Shipping method id
*
* @return ShippingMethod|null Required shipping method
*/
public function getOneById(CartInterface $cart, $shippingMethodId)
{
$shippingMethods = $this->get($cart);
return array_reduce($shippingMethods, function ($foundShippingMethod, ShippingMethod $shippingMethod) use($shippingMethodId) {
return $shippingMethodId === $shippingMethod->getId() ? $shippingMethod : $foundShippingMethod;
}, null);
}
示例8: setUp
public function setUp()
{
$source1 = new Source(array('generate' => function ($size) {
$r = '';
for ($i = 0; $i < $size; $i++) {
$r .= chr($i);
}
return $r;
}));
$source2 = new Source(array('generate' => function ($size) {
$r = '';
for ($i = $size - 1; $i >= 0; $i--) {
$r .= chr($i);
}
return $r;
}));
$sources = array($source1, $source2);
$mixer = new Mixer(array('mix' => function (array $sources) {
if (empty($sources)) {
return '';
}
$start = array_pop($sources);
return array_reduce($sources, function ($el1, $el2) {
return $el1 ^ $el2;
}, $start);
}));
$this->generator = new Generator($sources, $mixer);
}
示例9: getEmailRecipients
/**
* @param object|null $relatedEntity
* @param string|null $query
* @param Organization|null $organization
* @param int $limit
*
* @return array
*/
public function getEmailRecipients($relatedEntity = null, $query = null, Organization $organization = null, $limit = 100)
{
$emails = [];
foreach ($this->providers as $provider) {
if ($limit <= 0) {
break;
}
$args = new EmailRecipientsProviderArgs($relatedEntity, $query, $limit, array_reduce($emails, 'array_merge', []), $organization);
$recipients = $provider->getRecipients($args);
if (!$recipients) {
continue;
}
$limit = max([0, $limit - count($recipients)]);
if (!array_key_exists($provider->getSection(), $emails)) {
$emails[$provider->getSection()] = [];
}
$emails[$provider->getSection()] = array_merge($emails[$provider->getSection()], $recipients);
}
$result = [];
foreach ($emails as $section => $sectionEmails) {
$items = array_map(function (Recipient $recipient) {
return $this->emailRecipientsHelper->createRecipientData($recipient);
}, $sectionEmails);
$result[] = ['text' => $this->translator->trans($section), 'children' => array_values($items)];
}
return $result;
}
示例10: handle_auth_user_change
/**
* [Custom event handler which performs action]
*
* @param Doku_Event $event event object by reference
* @param mixed $param [the parameters passed as fifth argument to register_hook() when this
* handler was registered]
* @return void
*/
public function handle_auth_user_change(Doku_Event &$event, $param)
{
if ($event->data['type'] !== 'create') {
return;
}
$domains = array_map(function ($domain) {
return trim($domain);
}, explode(';', $this->getConf('_domainWhiteList')));
$email = $event->data['params'][3];
$checks = array(in_array(trim(substr(strrchr($email, "@"), 1)), $domains), (bool) preg_match($this->getConf('_emailRegex', '/@/'), $email));
if ($this->getConf('checksAnd', true)) {
$status = array_reduce($checks, function ($a, $b) {
return $a && $b;
}, true);
} else {
$status = array_reduce($checks, function ($a, $b) {
return $a || $b;
}, false);
}
if (!$status) {
$event->preventDefault();
$event->stopPropagation();
$event->result = false;
msg($this->getConf('_domainlistErrorMEssage'), -1);
}
}
示例11: getFieldsMetadata
/**
* @param string $classname
* @return array
*/
public function getFieldsMetadata($classname)
{
foreach ($this->getReflectionClass($classname)->getProperties() as $property) {
$properties = array_reduce($this->reader->getPropertyAnnotations($property), function ($reduced, $current) use($property, $classname) {
if ($current instanceof AbstractField) {
$current->name = $property->getName();
if (is_object($classname)) {
$property->setAccessible(true);
$current->value = $property->getValue($classname);
}
$key = get_class($current);
if (isset($reduced[$key])) {
if (!is_array($reduced[$key])) {
$reduced[$key] = [$reduced[$key]];
}
$reduced[$key][] = $current;
} else {
$reduced[$key] = $current;
}
return $reduced;
}
});
if (!is_null($properties)) {
$fields[$property->getName()] = $properties;
}
}
return $fields;
}
示例12: _removeMediaFiles
/**
* Remove orphans from disk
*
* @param array $filesToRemove
* @param InputInterface $input
* @param OutputInterface $output
* @return int
*/
protected function _removeMediaFiles(&$filesToRemove, InputInterface $input, OutputInterface $output)
{
if (count($filesToRemove) < 1) {
// Nothing to do
return 0;
}
$quiet = $input->getOption('quiet');
$totalSteps = $this->_getTotalSteps();
$currentStep = $this->_getCurrentStep();
$this->_advanceNextStep();
!$quiet && $output->writeln("<comment>Remove files from filesystem</comment> ({$currentStep}/{$totalSteps})");
$progress = new ProgressBar($output, count($filesToRemove));
$unlinkedCount = array_reduce($filesToRemove, function ($unlinkedCount, $info) use($progress, $quiet) {
$unlinked = unlink($info);
!$quiet && $progress->advance();
return $unlinkedCount + $unlinked;
}, 0);
if (!$quiet) {
$progress->finish();
if ($unlinkedCount < 1) {
$output->writeln("\n <error>NO FILES DELETED! do you even have write permissions?</error>\n");
} else {
$output->writeln("\n <info>...and it's gone... removed {$unlinkedCount} files</info>\n");
}
}
return $unlinkedCount;
}
示例13: validate
/**
* Validate
*
* @param mixed $value
* @return boolean
*/
public function validate($value)
{
$messenger = $this->messenger->clear();
return array_reduce($this->func, function (&$result, $func) use($value, $messenger) {
return $result && $func($value, $messenger);
}, true);
}
示例14: formatColumns
private function formatColumns()
{
return array_reduce($this->columns, function ($c, Column $column) {
$c[] = $column->toArray();
return $c;
}, []);
}
示例15: getLatest
/**
* Fetches the version of the latest stable release.
*
* By Default, this uses the GitHub API (v3) and only returns refs that begin with
* 'tags/release-'. Because GitHub returns the refs in alphabetical order,
* we need to reduce the array to a single value, comparing the version
* numbers with version_compare().
*
* If $service is set to VERSION_SERVICE_ZEND this will fall back to calling the
* classic style of version retreival.
*
*
* @see http://developer.github.com/v3/git/refs/#get-all-references
* @link https://api.github.com/repos/zendframework/zf2/git/refs/tags/release-
* @link http://framework.zend.com/api/zf-version?v=2
* @param string $service Version Service with which to retrieve the version
* @return string
*/
public static function getLatest($service = self::VERSION_SERVICE_GITHUB)
{
if (null === static::$latestVersion) {
static::$latestVersion = 'not available';
if ($service == self::VERSION_SERVICE_GITHUB) {
$url = 'https://api.github.com/repos/zendframework/zf2/git/refs/tags/release-';
$apiResponse = Json::decode(file_get_contents($url), Json::TYPE_ARRAY);
// Simplify the API response into a simple array of version numbers
$tags = array_map(function ($tag) {
return substr($tag['ref'], 18);
// Reliable because we're filtering on 'refs/tags/release-'
}, $apiResponse);
// Fetch the latest version number from the array
static::$latestVersion = array_reduce($tags, function ($a, $b) {
return version_compare($a, $b, '>') ? $a : $b;
});
} elseif ($service == self::VERSION_SERVICE_ZEND) {
$handle = fopen('http://framework.zend.com/api/zf-version?v=2', 'r');
if (false !== $handle) {
static::$latestVersion = stream_get_contents($handle);
fclose($handle);
}
}
}
return static::$latestVersion;
}