本文整理汇总了PHP中array_diff函数的典型用法代码示例。如果您正苦于以下问题:PHP array_diff函数的具体用法?PHP array_diff怎么用?PHP array_diff使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了array_diff函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __construct
/**
* Constructs a book dialog
* $action - GET or POST action to take.
* $inclusions - NULL (in which case it does nothing), or an array of book IDs to include.
* $exclusions - NULL (in which case it does nothing), or an array of book IDs to exclude.
*/
public function __construct($header, $info_top, $info_bottom, $action, $inclusions, $exclusions)
{
$this->view = new Assets_View(__FILE__);
$caller = $_SERVER["PHP_SELF"] . "?" . http_build_query(array());
$this->view->view->caller = $caller;
$this->view->view->header = $header;
$this->view->view->info_top = $info_top;
$this->view->view->info_bottom = $info_bottom;
$this->view->view->action = $action;
$database_books = Database_Books::getInstance();
$book_ids = $database_books->getIDs();
if (is_array($inclusions)) {
$book_ids = $inclusions;
}
if (is_array($exclusions)) {
$book_ids = array_diff($book_ids, $exclusions);
$book_ids = array_values($book_ids);
}
foreach ($book_ids as $id) {
$book_names[] = $database_books->getEnglishFromId($id);
}
$this->view->view->book_ids = $book_ids;
$this->view->view->book_names = $book_names;
$this->view->render("books2.php");
Assets_Page::footer();
die;
}
示例2: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$path = $input->getArgument('path');
if (!file_exists($path)) {
$output->writeln("{$path} is not a file or a path");
}
$filePaths = [];
if (is_file($path)) {
$filePaths = [realpath($path)];
} elseif (is_dir($path)) {
$filePaths = array_diff(scandir($path), array('..', '.'));
} else {
$output->writeln("{$path} is not known.");
}
$generator = new StopwordGenerator($filePaths);
if ($input->getArgument('type') === 'json') {
echo json_encode($this->toArray($generator->getStopwords()), JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
echo json_last_error_msg();
die;
$output->write(json_encode($this->toArray($generator->getStopwords())));
} else {
$stopwords = $generator->getStopwords();
$stdout = fopen('php://stdout', 'w');
echo 'token,freq' . PHP_EOL;
foreach ($stopwords as $token => $freq) {
fputcsv($stdout, [utf8_encode($token), $freq]) . PHP_EOL;
}
fclose($stdout);
}
}
示例3: list_
/**
* List users.
*
* ## OPTIONS
*
* [--role=<role>]
* : Only display users with a certain role.
*
* [--<field>=<value>]
* : Control output by one or more arguments of get_users().
*
* [--network]
* : List all users in the network for multisite.
*
* [--field=<field>]
* : Prints the value of a single field for each user.
*
* [--fields=<fields>]
* : Limit the output to specific object fields.
*
* [--format=<format>]
* : Accepted values: table, csv, json, count. Default: table
*
* ## AVAILABLE FIELDS
*
* These fields will be displayed by default for each user:
*
* * ID
* * user_login
* * display_name
* * user_email
* * user_registered
* * roles
*
* These fields are optionally available:
*
* * user_pass
* * user_nicename
* * user_url
* * user_activation_key
* * user_status
* * spam
* * deleted
* * caps
* * cap_key
* * allcaps
* * filter
*
* ## EXAMPLES
*
* wp user list --field=ID
*
* wp user list --role=administrator --format=csv
*
* wp user list --fields=display_name,user_email --format=json
*
* @subcommand list
*/
public function list_($args, $assoc_args)
{
if (\WP_CLI\Utils\get_flag_value($assoc_args, 'network')) {
if (!is_multisite()) {
WP_CLI::error('This is not a multisite install.');
}
$assoc_args['blog_id'] = 0;
if (isset($assoc_args['fields'])) {
$fields = explode(',', $assoc_args['fields']);
$assoc_args['fields'] = array_diff($fields, array('roles'));
} else {
$assoc_args['fields'] = array_diff($this->obj_fields, array('roles'));
}
}
$formatter = $this->get_formatter($assoc_args);
if ('ids' == $formatter->format) {
$assoc_args['fields'] = 'ids';
} else {
$assoc_args['fields'] = 'all_with_meta';
}
$users = get_users($assoc_args);
if ('ids' == $formatter->format) {
echo implode(' ', $users);
} else {
$it = WP_CLI\Utils\iterator_map($users, function ($user) {
if (!is_object($user)) {
return $user;
}
$user->roles = implode(',', $user->roles);
return $user;
});
$formatter->display_items($it);
}
}
示例4: index
/**
* Display a listing of the resource.
*
* @param Store $store
*
* @return Response
*/
public function index(Store $store)
{
// ImportedProduct::truncate();
// ErrorProduct::truncate();
JavaScript::put(['url' => '/products', 'os_total' => OsProduct::count(), 'imported_total' => ImportedProduct::count(), 'resource' => array_values(array_diff(OsProduct::orderBy('products_id', 'desc')->lists('products_id')->toArray(), ImportedProduct::orderBy('os_id', 'desc')->lists('os_id')->toArray(), ErrorProduct::orderBy('os_id', 'desc')->lists('os_id')->toArray()))]);
return view('importer.index', ['resource' => 'Products']);
}
示例5: getTransportMock
public function getTransportMock($args = 'testuri', $changeMethods = array())
{
//Array XOR
$defaultMockMethods = array('getDomFromBackend', 'getJsonFromBackend', 'checkLogin', 'initConnection', '__destruct', '__construct');
$mockMethods = array_merge(array_diff($defaultMockMethods, $changeMethods), array_diff($changeMethods, $defaultMockMethods));
return $this->getMock('jackalope_transport_DavexClient_Mock', $mockMethods, array($args));
}
示例6: _makeRequest
/**
* Sends a request to the REST API service and does initial processing
* on the response.
*
* @param string $op Name of the operation for the request
* @param array $query Query data for the request (optional)
* @throws Zend_Service_Exception
* @return DOMDocument Parsed XML response
*/
protected function _makeRequest($op, $query = null)
{
if ($query != null) {
$query = array_diff($query, array_filter($query, 'is_null'));
$query = '?' . http_build_query($query);
}
$this->_http->setUri($this->_baseUri . $op . '.do' . $query);
$response = $this->_http->request('GET');
if ($response->isSuccessful()) {
$doc = new DOMDocument();
$doc->loadXML($response->getBody());
$xpath = new DOMXPath($doc);
$list = $xpath->query('/status/code');
if ($list->length > 0) {
$code = $list->item(0)->nodeValue;
if ($code != 0) {
$list = $xpath->query('/status/message');
$message = $list->item(0)->nodeValue;
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception($message, $code);
}
}
return $doc;
}
/**
* @see Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
throw new Zend_Service_Exception($response->getMessage(), $response->getStatus());
}
示例7: __save
/**
* Fetches hashed data from db and put into instance
*/
private function __save()
{
$class = $this->class;
$database = new database($class::$database);
if ($this->get_attributes()) {
$columns = "(`{$class::$entity_id_column}`, `{$class::$key_column}`, `{$class::$value_column}`, `date_added`, `date_updated`)";
$placeholders = $values = $duplicate_keys = array();
foreach ($this->get_attributes() as $key => $value) {
$placeholders[] = "(%d, %s, %s, NOW(), NOW())";
$values[] = $this->entity_id;
$values[] = $key;
$values[] = $value;
$duplicate_keys[] = "`{$class::$value_column}` = VALUES(`{$class::$value_column}`)";
}
$duplicate_keys[] = '`date_updated` = VALUES(`date_updated`)';
$database->query("INSERT INTO {$class::$table} {$columns} VALUES " . implode(', ', $placeholders) . " ON DUPLICATE KEY UPDATE " . implode(', ', $duplicate_keys), $values);
}
if ($unset_keys = array_diff($this->original_keys, array_keys($this->get_attributes()))) {
// we unset something
print_r(array($this->entity_id, $unset_keys));
database::enable_log();
$database->query("DELETE FROM {$class::$table} WHERE `{$class::$entity_id_column}` = %d AND `{$class::$key_column}` IN (%s)", array($this->entity_id, $unset_keys));
}
return true;
}
示例8: getAccessibilityScope
/**
* Get Global Application CMS accessibility scope.
*
* @access public
* @static
* @uses Core\Config()
*
* @return array
*/
public static function getAccessibilityScope()
{
$scope = glob(Core\Config()->paths('mode') . 'controllers' . DIRECTORY_SEPARATOR . '*.php');
$builtin_scope = array('CMS\\Controllers\\CMS');
$builtin_actions = array();
$accessibility_scope = array();
foreach ($builtin_scope as $resource) {
$builtin_actions = array_merge($builtin_actions, get_class_methods($resource));
}
$builtin_actions = array_filter($builtin_actions, function ($action) {
return !in_array($action, array('create', 'show', 'edit', 'delete', 'export'), true);
});
foreach ($scope as $resource) {
$resource = basename(str_replace('.php', '', $resource));
if ($resource !== 'cms') {
$controller_name = '\\CMS\\Controllers\\' . $resource;
$controller_class = new \ReflectionClass($controller_name);
if (!$controller_class->isInstantiable()) {
continue;
}
/* Create instance only if the controller class is instantiable */
$controller_object = new $controller_name();
if ($controller_object instanceof CMS\Controllers\CMS) {
$accessibility_scope[$resource] = array_diff(get_class_methods($controller_name), $builtin_actions);
array_push($accessibility_scope[$resource], 'index');
foreach ($accessibility_scope[$resource] as $key => $action_with_acl) {
if (in_array($action_with_acl, $controller_object->skipAclFor, true)) {
unset($accessibility_scope[$resource][$key]);
}
}
}
}
}
return $accessibility_scope;
}
示例9: _afterSave
/**
* Perform actions after object save
*
* @param Mage_Widget_Model_Widget_Instance $object
* @return Mage_Widget_Model_Mysql4_Widget_Instance
*/
protected function _afterSave(Mage_Core_Model_Abstract $object)
{
$pageTable = $this->getTable('widget/widget_instance_page');
$pageLayoutTable = $this->getTable('widget/widget_instance_page_layout');
$layoutUpdateTable = $this->getTable('core/layout_update');
$layoutLinkTable = $this->getTable('core/layout_link');
$write = $this->_getWriteAdapter();
$select = $write->select()->from($pageTable, array('page_id'))->where('instance_id = ?', $object->getId());
$pageIds = $write->fetchCol($select);
$removePageIds = array_diff($pageIds, $object->getData('page_group_ids'));
$select = $write->select()->from($pageLayoutTable, array('layout_update_id'))->where('page_id in (?)', $pageIds);
$removeLayoutUpdateIds = $write->fetchCol($select);
$this->_deleteWidgetInstancePages($removePageIds);
$write->delete($pageLayoutTable, $write->quoteInto('page_id in (?)', $pageIds));
$this->_deleteLayoutUpdates($removeLayoutUpdateIds);
foreach ($object->getData('page_groups') as $pageGroup) {
$pageLayoutUpdateIds = $this->_saveLayoutUpdates($object, $pageGroup);
$data = array('group' => $pageGroup['group'], 'layout_handle' => $pageGroup['layout_handle'], 'block_reference' => $pageGroup['block_reference'], 'for' => $pageGroup['for'], 'entities' => $pageGroup['entities'], 'template' => $pageGroup['template']);
$pageId = $pageGroup['page_id'];
if (in_array($pageGroup['page_id'], $pageIds)) {
$write->update($pageTable, $data, $write->quoteInto('page_id = ?', $pageId));
} else {
$write->insert($pageTable, array_merge(array('instance_id' => $object->getId()), $data));
$pageId = $write->lastInsertId();
}
foreach ($pageLayoutUpdateIds as $layoutUpdateId) {
$write->insert($pageLayoutTable, array('page_id' => $pageId, 'layout_update_id' => $layoutUpdateId));
}
}
return parent::_afterSave($object);
}
示例10: test_certificate_get_teachers
public function test_certificate_get_teachers()
{
global $DB;
$certificate = $this->generator->create_instance(array('course' => $this->course->id));
$coursemodule = get_coursemodule_from_instance('certificate', $certificate->id);
$studentroleid = $DB->get_record('role', array('shortname' => 'student'), 'id')->id;
$teacherroleid = $DB->get_record('role', array('shortname' => 'editingteacher'), 'id')->id;
$teacheruserarray = array();
for ($i = 0; $i < 10; $i++) {
$teacheruserarray[] = $this->getDataGenerator()->create_user(array('email' => "teacherdoge{$i}@dogeversity.doge", 'username' => "Dr. doge{$i}"));
// Enrol the user as a teacher.
$this->getDataGenerator()->enrol_user(end($teacheruserarray)->id, $this->course->id, $teacherroleid);
}
// Enrol a single student and issue his/her a certificate.
$studentuser = $this->getDataGenerator()->create_user(array('email' => "studentdoge@dogeversity.doge", 'username' => "dogemanorwomen"));
$this->getDataGenerator()->enrol_user($studentuser->id, $this->course->id, $studentroleid);
certificate_get_issue($this->course, $studentuser, $certificate, $coursemodule);
$certificateteacherarray = certificate_get_teachers(null, $studentuser, $coursemodule, $coursemodule);
// Acquire the ids (not all attributes are equal considering db transaction can have auto values).
$teacheruserids = array_map(create_function('$t', 'return $t->id;'), $teacheruserarray);
$certificateteacherids = array_map(create_function('$c', 'return $c->id;'), $certificateteacherarray);
/**
* Ensure that two arrays have one-to-one correspondence, that is each
* is a subset of each other.
*/
$emptyarray = array();
$this->assertEquals(array_diff($teacheruserids, $certificateteacherids), $emptyarray);
}
示例11: normalize
/**
* {@inheritdoc}
*/
public function normalize($product, $format = null, array $context = [])
{
if (!$this->serializer instanceof NormalizerInterface) {
throw new \LogicException('Serializer must be a normalizer');
}
$context['entity'] = 'product';
$data = [];
if ($product->getGroupCodes()) {
$groups = explode(',', $product->getGroupCodes());
if ($product->getVariantGroup()) {
$variantGroup = $product->getVariantGroup()->getCode();
$groups = array_diff($groups, [$variantGroup]);
}
} else {
$groups = [];
}
$data[self::FIELD_FAMILY] = $product->getFamily() ? $product->getFamily()->getCode() : null;
$data[self::FIELD_GROUPS] = $groups;
$data[self::FIELD_VARIANT_GROUP] = $product->getVariantGroup() ? $product->getVariantGroup()->getCode() : null;
$data[self::FIELD_CATEGORY] = $product->getCategoryCodes() ? explode(',', $product->getCategoryCodes()) : [];
$data[self::FIELD_ENABLED] = $product->isEnabled();
$data[self::FIELD_ASSOCIATIONS] = $this->normalizeAssociations($product->getAssociations());
$data[self::FIELD_VALUES] = $this->normalizeValues($product->getValues(), $format, $context);
if (isset($context['resource'])) {
$data['resource'] = $context['resource'];
}
return $data;
}
示例12: passMenu
public function passMenu()
{
// return if no Itemid or selection is set
if (!$this->request->Itemid || empty($this->selection)) {
return $this->pass($this->params->inc_noitemid);
}
$menutype = 'type.' . self::getMenuType();
// return true if menu type is in selection
if (in_array($menutype, $this->selection)) {
return $this->pass(true);
}
// return true if menu is in selection
if (in_array($this->request->Itemid, $this->selection)) {
return $this->pass($this->params->inc_children != 2);
}
if (!$this->params->inc_children) {
return $this->pass(false);
}
$parent_ids = $this->getMenuParentIds($this->request->Itemid);
$parent_ids = array_diff($parent_ids, array('1'));
foreach ($parent_ids as $id) {
if (!in_array($id, $this->selection)) {
continue;
}
return $this->pass(true);
}
return $this->pass(false);
}
示例13: testNormalizeToArray
public function testNormalizeToArray()
{
$normalized = ArrayUtil::normalizeToArray($this->arrayTemplate, $this->arrayOld);
$tmplKeys = array_keys($this->arrayTemplate);
$oldKeys = array_keys($this->arrayOld);
$keepKeys = array_intersect($tmplKeys, $oldKeys);
$newKeys = array_diff($tmplKeys, $oldKeys);
$deleteKeys = array_diff($oldKeys, $tmplKeys);
// All keys in the template must be present:
foreach ($tmplKeys as $key) {
$this->assertArrayHasKey($key, $normalized, "Array lost a key!");
}
// All fields not specified must be removed:
foreach ($deleteKeys as $key) {
$this->assertArrayNotHasKey($key, $normalized);
}
// All new fields must inherit specified default values:
foreach ($newKeys as $key) {
$this->assertEquals($this->arrayTemplate[$key], $normalized[$key], "Didn't inherit default value!");
}
// All fields must retain their original values, if they didn't need to
// be initialized with default values:
foreach ($keepKeys as $key) {
$this->assertEquals($this->arrayOld[$key], $normalized[$key], "Array value changed when it shouldn't have!");
}
}
示例14: from
/**
* @param \ReflectionClass|string
* @return self
*/
public static function from($from)
{
$from = new \ReflectionClass($from instanceof \ReflectionClass ? $from->getName() : $from);
if (PHP_VERSION_ID >= 70000 && $from->isAnonymous()) {
$class = new static('anonymous');
} else {
$class = new static($from->getShortName(), new PhpNamespace($from->getNamespaceName()));
}
$class->type = $from->isInterface() ? 'interface' : (PHP_VERSION_ID >= 50400 && $from->isTrait() ? 'trait' : 'class');
$class->final = $from->isFinal() && $class->type === 'class';
$class->abstract = $from->isAbstract() && $class->type === 'class';
$class->implements = $from->getInterfaceNames();
$class->documents = $from->getDocComment() ? array(preg_replace('#^\\s*\\* ?#m', '', trim($from->getDocComment(), "/* \r\n\t"))) : array();
if ($from->getParentClass()) {
$class->extends = $from->getParentClass()->getName();
$class->implements = array_diff($class->implements, $from->getParentClass()->getInterfaceNames());
}
foreach ($from->getProperties() as $prop) {
if ($prop->getDeclaringClass()->getName() === $from->getName()) {
$class->properties[$prop->getName()] = Property::from($prop);
}
}
foreach ($from->getMethods() as $method) {
if ($method->getDeclaringClass()->getName() === $from->getName()) {
$class->methods[$method->getName()] = Method::from($method)->setNamespace($class->namespace);
}
}
return $class;
}
示例15: saveLangueList
public function saveLangueList($con = null)
{
if (!$this->isValid()) {
throw $this->getErrorSchema();
}
if (!isset($this->widgetSchema['langue_list'])) {
// somebody has unset this widget
return;
}
if (null === $con) {
$con = $this->getConnection();
}
$existing = $this->object->Langue->getPrimaryKeys();
$values = $this->getValue('langue_list');
if (!is_array($values)) {
$values = array();
}
$unlink = array_diff($existing, $values);
if (count($unlink)) {
$this->object->unlink('Langue', array_values($unlink));
$delete_log = new DeleteLog();
$delete_log->setGuid(Guid::generate());
$delete_log->setExtra('exposition_visiteurneeds_id: "' . $this->getObject()->getGuid() . '"|langue_id: "' . implode('", "', array_values($unlink)) . '"');
$delete_log->setModelName('LangueExpositionVisiteurNeeds');
$delete_log->save();
}
$link = array_diff($values, $existing);
if (count($link)) {
$this->object->link('Langue', array_values($link));
}
}