#array_values()
Explore tagged Tumblr posts
Text
PHP / array_values
Esta funcion nos permite obtener unicamente los valores de un array, igunorando las claves de esta, espero les resulte de utilidad!
Bienvenidos sean a este post, hoy veremos una funcion para los arrays. Esta funcion nos devuelve los valores de un array, veamos como es su sintaxis: array_values(array) Simplemente pasamos el array y este nos devolvera los valores contenidos en este, veamos un ejemplo y para ello debemos crear un nuevo archivo con el nombre de array.php y le agregaremos el sigeitne…
View On WordPress
0 notes
Link
Check the most useful PHP functions like:
is_array($arr) in_array($search, $arr, $type) sizeof($arr) array_merge($arr1, $arr2) array_keys($arr) array_values($arr) array_push($arr, $val) array_pop($arr) . . . more
#php#php functions#php array functions#array functions#array#is_array()#in_array()#array_merge()#array_keys()#array_values()#array_push()#array_pop()#ksort()#array_rand()#array_filter()#sort()
0 notes
Text
How To Use Chart JS In Laravel
The fundamentals of Chart.js are quite straightforward. First, we must install Chart.js into our project. Depending on the settings of your project, you may be installing it using npm or bower, or you may link to a constructed version via a CDN or clone/build from GitHub. Simply connecting to the created CDN version in the sample's blade file would suffice for this brief example. A The fundamentals of Chart js are quite straightforward. First, we must install Chart js into our project. Depending on the settings of your project, you may be installing it using npm or bower, or you may link to a constructed version via a CDN or clone/build from GitHub. In our examples, we'll only link to the built-in CDN version for the purposes of this brief demonstration. We'll just plot the ages of the app users in this case. We're presuming you've already set up the Laravel auth scaffolding and carried out the required migrations to make a Users table. If not, take a look at the information here or modify it for the model you're using for your chart's data. Therefore, before creating any users at random, we'll first add an age column to our Users table. For more information, see our post on how to use faker to create random users, however for this demonstration, let's make a database migration to add an age column by using: add age to users table php artisan make:migration —table='users' To change the up function to: edit this file in the database migrations directory. Schema::table('Users', function (Blueprint $table) { $table->int('age')->nullable(); }); Run php artisan migrate after that, and your Users table should now contain an age column. Visit /database/factories/UserFactory now, and add the following at the end of the array: 'age' is represented by $faker->numberBetween($min = 20, $max = 80), The complete return is thus: return ; Run the following commands to build a UsersTableSeeder: make:seeder UsersTableSeeder in PHP This will produce UsersTableSeeder.php in the database. The run function should include the following: factory(AppUser::class, 5)->create(); When this is executed, 5 users will be created; modify 5 to the number of users you need. After that, we must open DatabaseSeeder.php in /database/seeds and uncomment the code in the run() function. Finally, execute php artisan db:seed. Five new users should appear, each of whom has an age. For our Charts page, we will now develop a model, controller, views, and routes. Run the following command in PHP: make:controller ChartController —model=Chart. To the file /app/Http/Controllers/ChartController.php, add the following: use AppUser; use AppChart; use DB; ... public function index() { // Get users grouped by age $groups = DB::table('users') ->select('age', DB::raw('count(*) as total')) ->groupBy('age') ->pluck('total', 'age')->all(); // Generate random colours for the groups for ($i=0; $ilabels = (array_keys($groups)); $chart->dataset = (array_values($groups)); $chart->colours = $colours; return view('charts.index', compact('chart')); } The random colour scheme is one example of the exciting things you can do with the controller's data, though you can also specify hardcoded colours if you'd choose. In /resources/views/charts/, we must now create an index.blade.php file and add the following (depending on your blade setup and layout; here is an example): Laravel Chart Example Chart Demo Finally, we need to add the following to /routes/web.php: Route::get('/charts', 'ChartController@index')->name('charts'); Go to at your-project-name.test/charts now. Although this should serve as a good starting point for your understanding of the fundamentals of charts and graphs in Laravel, you may refer to the Chart.js documentation for more details on customizing your charts. Read the full article
0 notes
Text
Today I learned that when you json_encode a php array with numbered keys it is ordered by the keys, no matter what the current order.
This makes sense if you’re looking at it based on how javascript arrays work, but I assumed (wrongly) that it would simply convert it to an object instead if they were out of order.
It’s fine, it was an easy fix: natsort($array); $array = array_values($array); Fun fact about the cbz archive, the functional spec is loose enough that you have to natural sort to contents to put them in order (and account for nested directories)
0 notes
Text
더 짧아진 Which 함수
더 짧아진 Which 함수
지난 번 포스팅에서 말한 더 개선한 which함수를 조금 더 개선해보았다. 지난 번에는 Enum을 사용하다보니 select case문이 비교연산의 갯수에 비례하여 커졌다. 이번에는 이넘도 저넘도 필요없다. 연산자를 문자열로 전달하면 된다. 이렇게 짧아진 이유는 Application.Evaluate() 덕분이다. Application.Evaluate()은 문자열로 표시된 수식을 평가하여 적절한 결과를 돌려준다. Function which2(array_values, oper As String, lookup) As Long() Dim i As Long, lb As Long, ub As Long Dim index() As Long, cnt As Long lb = LBound(array_values) ub =…
View On WordPress
0 notes
Text
[Laravel][Testing] Display clearly array not equals error messages
Problem
When assertEqual asserting was failed, I can’t not known where the path of properies is not match.
Example: Assume I have many configs(contains inputs and expected result) With bellow test, I will receive the bellow message.
private const CONFIGS = [ [ 'params' => [ 'level' => JlptRank::N4, 'parts_score' => [ JlptCategoryConstant::JLPT_VOCABULARY__VALUE => 50, JlptCategoryConstant::JLPT_READING__VALUE => 50, JlptCategoryConstant::JLPT_LISTENING__VALUE => 50, ] ], 'expect_return_value' => JlptRank::RANK_A ], // ... ];
Test code:
/** @test */ public function it_returns_expect_results() { foreach (self::CONFIGS as $config) { $this->assertEquals( $config['expect_return_value'], JlptRank::calculate_Jlpt_rank(...array_values($config['params'])) ); } }
Test result:
Failed asserting that two strings are equal. Expected :'C' Actual :'D'
It is hard to find where is the *config that happen don’t match.*
Solution
Merge inputs and expected results in to array, and comparsion it.
/** @test */ public function it_returns_expect_results() { foreach (self::CONFIGS as $config) { $this->assertEquals( json_encode($config), json_encode(array_merge($config, ['expect_return_value' => JlptRank::calculate_Jlpt_rank(...array_values($config['params']))])) ); } }
Test result will be:
Failed asserting that two strings are equal. Expected :'{"params":{"level":4,"parts_score":{"91":10,"93":60,"94":10}},"expect_return_value":"C"}' Actual :'{"params":{"level":4,"parts_score":{"91":10,"93":60,"94":10}},"expect_return_value":"D"}'
Now you can easily see which properties don’t match.
0 notes
Text
PHP Phun #2: Array Methods
PHP Phun #2: Arrays (And Wonked Up Array Methods)
The Topic: Every Array is Associative
People (rightly and justifiably) love to give PHP grief for its native array methods. There’s a ton of inconsistencies on function arguments and function return values that feel unintuitive.
Even apart from array functions themselves, there’s a lot of confusion about arrays in general. The one thing you must remember, above all, is that all arrays in php are hash tables.
ALL arrays are key-value maps. They are all associative arrays. Even if you’re just shoving values into an array without specifying keys, it’s still an associative array; php has just decided to be nice enough to give you keys that happen to be consecutive integers starting from zero.
Even though I know that all php arrays are associative arrays, some odd and unexpected consequences of this still get me.
The Problem: The Return of Array Filter
I was investigating the cause of a bug when I nailed it down to the return value of an array_filter call. A rough approximation of the code was something like this:
$filteredElement = array_filter(function ($element) {....}, $array)[0];
Now with this filter, I was 100% certain that the function would always return exactly one value, but for some reason there were times where $filteredElement was null. If I knew I was always getting a value back, why was it empty?
Well, because the return of array_filter is an associative array and it preserves the original naming of the keys.
Let’s say the array I passed in was this one:
[‘zelda’, ‘link’, ‘gannon’]
Under the hood, that’s secretly:
[ ‘0’ => ‘zelda’, ‘1’ => ‘link’, ‘2’ => ‘gannon’].
If my array_filter returned back the ‘gannon’ element, the array I’d be getting back would actually be:
[ ‘2’ => ‘gannon’].
This is not what’d you’d expect, as a lot of other languages would give you back
[ ‘0’ => ‘gannon’ ].
Because I was getting back [ ‘2’ => ‘gannon’], I wasn’t getting anything when I tried to access the element with zero as my key, [0].
One thing you can do to prevent this is wrap the array_filter in array_values. This will take all the values from the array and put them in a new array with numeric, sequential indexed keys.
0 notes
Text
How drunk do you need to be...
array_map('\strval', array_unique(array_merge(array_unique(array_values(array_map([$this, 'getValue'], $array1))), array_unique(array_values(array_map([$this, 'getValue'], $array2))), array_unique(array_values(array_map([$this, 'getValue'], $array3)))));
0 notes
Photo

Genişletilmiş Dizi Nesne Sınıfı <?php class genisletilmisDiziNesnesi extends ArrayObject { private $dizi; public function __construct(){ if (is_array(func_get_arg(0))) $this->dizi = func_get_arg(0); else $this->dizi = func_get_args(); parent::__construct($this->dizi); } public function each($callback){ $yineleyici = $this->getIterator(); while($yineleyici->valid()) { $callback($yineleyici->current()); $yineleyici->next(); } } public function haric(){ $args = func_get_args(); return array_values(array_diff($this->dizi,$args)); } public function ilk(){ return $this->dizi[0]; } public function sira($deger){ return array_search($deger,$this->dizi); } public function denetle(){ echo print_r($this->dizi, true); } public function son(){ return $this->dizi; } public function terscevir($uygula=false){ if(!$uygula){ return array_reverse($this->dizi); }else{ $dizi = array_reverse($this->dizi); $this->dizi = $dizi; parent::__construct($this->dizi); return $this->dizi; } } public function shift(){ $eleman = array_shift($this->dizi); parent::__construct($this->dizi); return $eleman; } public function pop(){ $eleman = array_pop($this->dizi); parent::__construct($this->dizi); return $eleman; } } function yazdir($deger){ echo $deger; } $dizi = new genisletilmisDiziNesnesi(); $dizi->each("yazdir"); echo "<br>"; print_r($dizi->haric(2,3,4)); $dizi->denetle(); echo $dizi->sira(5); echo "<br>"; print_r($dizi->terscevir()); print_r($dizi->terscevir(true)); echo $dizi->shift(); echo "<br>"; echo $dizi->pop(); echo "<br>"; echo $dizi->son(); echo "<br>"; echo $dizi->ilk(); ?>
0 notes
Text
How to Create a WordPress Intranet for Your Organization
Do you want to create a WordPress intranet for your organization? WordPress is a powerful platform with tons of flexible options that makes it ideal to be used as your company’s intranet. In this article, we will show you how to create a WordPress intranet for your organization while keeping it private and secure.
What is Intranet or Extranet? Why Use WordPress as Your Intranet Platform?
Intranet or Extranet is a communications platform used by an organization for communication, file sharing, announcements, and other organizational activities.
WordPress is an excellent platform to build your organization’s intranet or extranet. It is easy to maintain, open source, and gives you access to thousands of WordPress plugins to add new features when needed.
An intranet runs on an organization’s private network. Typically, an office IT system is connected via cable or wireless network adapters. One computer on the network can be used as the web server and host a WordPress website.
Follow the instructions in our guide on how to install WordPress on a Windows network using WAMP or install WordPress on a Mac computer using MAMP to start your WordPress intranet.
On the other hand, an extranet is an intranet platform accessible to a larger network or public internet. In plain English, this could be a website publicly accessible but restricted to authorized users only.
It is particularly useful if your organization is distributed across different geographic locations.
To create your WordPress extranet, you’ll need a WordPress hosting account and a domain name. After that, you can install WordPress and then set it up to be used as your organization’s intranet.
Once you have installed WordPress as your intranet, the next step is to convert it into a communications hub for your organization.
To do that, you’ll be using several WordPress plugins. We will show you the basic setup that will serve as the foundation for your WordPress intranet to grow and meet your organization’s goals.
Setting Up BuddyPress as Your WordPress Intranet Hub
BuddyPress is a sister project of WordPress. It converts your WordPress website into a social network. Here are some of the things a BuddyPress powered intranet can do:
You will be able to invite users to register on company intranet
Users will be able to create extended user profiles
Activity streams allow users to follow latest updates like Twitter or Facebook
You will be able to create user groups to sort users into departments or teams
Users can follow each other as friends
Users can send private messages to each other
You can add new features by adding third-party plugins
You’ll have plenty of design options with WordPress themes for BuddyPress
To get started, first you will need to install and activate BuddyPress plugin. For more details, see our step by step guide on how to install a WordPress plugin.
Upon activation, head over to Settings » BuddyPress page to configure plugin settings.
For complete step by step instructions see our guide on how to turn WordPress into a social network with BuddyPress.
Secure Your WordPress Intranet with All-in-One Intranet
If you are running a WordPress intranet on local server, then you can secure it by limiting access to internal IPs in your .htaccess file.
However, if you are running an Extranet, then your users may be accessing the intranet from different networks and IP addresses.
To make sure that only authorized users get access to your company intranet, you need to make your extranet private and accessible to only registered users.
For that, you’ll need to install and activate the All-in-One Intranet plugin. For more details, see our step by step guide on how to install a WordPress plugin.
Upon activation, head over to Settings » All-in-One Intranet page to configure the plugin settings.
First you need to check the box next to ‘Force site to be entirely private’ option. This will make all pages of your WordPress site completely private.
The only thing this plugin will not make private is the files in your uploads directory. Don’t worry, we will show you how to protect it later in this article.
Next, you need to provide a URL where you want users to be redirected when they are logged in. This could be any page on your intranet.
Lastly, you can automatically logout inactive users after a certain number of minutes.
Don’t forget to click on the save changes button to store your settings.
Securing Media Uploads on your WordPress Intranet
Making your website completely private doesn’t affect media files. If someone knows the exact URL of a file, then they can access it without any restriction.
Let’s change that.
For better protection, we will be redirecting all requests made to the uploads folder to a simple PHP script.
This php script will check if a user is logged in. If they are, then it will serve the file. Otherwise, the user will be redirected to the login page.
First you need to create a new file on your computer using a plain text editor like Notepad. After that you need to copy and paste the following code and save the file as download-file.php on your desktop.
<?php require_once('wp-load.php'); is_user_logged_in() || auth_redirect(); list($basedir) = array_values(array_intersect_key(wp_upload_dir(), array('basedir' => 1)))+array(NULL); $file = rtrim($basedir,'/').'/'.str_replace('..', '', isset($_GET[ 'file' ])?$_GET[ 'file' ]:''); if (!$basedir || !is_file($file)) { status_header(404); die('404 — File not found.'); } $mime = wp_check_filetype($file); if( false === $mime[ 'type' ] && function_exists( 'mime_content_type' ) ) $mime[ 'type' ] = mime_content_type( $file ); if( $mime[ 'type' ] ) $mimetype = $mime[ 'type' ]; else $mimetype = 'image/' . substr( $file, strrpos( $file, '.' ) + 1 ); header( 'Content-Type: ' . $mimetype ); // always send this if ( false === strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS' ) ) header( 'Content-Length: ' . filesize( $file ) ); $last_modified = gmdate( 'D, d M Y H:i:s', filemtime( $file ) ); $etag = '"' . md5( $last_modified ) . '"'; header( "Last-Modified: $last_modified GMT" ); header( 'ETag: ' . $etag ); header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 100000000 ) . ' GMT' ); // Support for Conditional GET $client_etag = isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ? stripslashes( $_SERVER['HTTP_IF_NONE_MATCH'] ) : false; if( ! isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) $_SERVER['HTTP_IF_MODIFIED_SINCE'] = false; $client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ); // If string is empty, return 0. If not, attempt to parse into a timestamp $client_modified_timestamp = $client_last_modified ? strtotime( $client_last_modified ) : 0; // Make a timestamp for our most recent modification... $modified_timestamp = strtotime($last_modified); if ( ( $client_last_modified && $client_etag ) ? ( ( $client_modified_timestamp >= $modified_timestamp) && ( $client_etag == $etag ) ) : ( ( $client_modified_timestamp >= $modified_timestamp) || ( $client_etag == $etag ) ) ) { status_header( 304 ); exit; } readfile( $file );
Now connect to your website using an FTP client. Once connected, upload the file you just created to /wp-contents/uploads/ folder on your website.
Next, you need edit the .htaccess file in your website’s root folder. Add the following code at the bottom of your .htaccess file:
RewriteCond %{REQUEST_FILENAME} -s RewriteRule ^wp-content/uploads/(.*)$ download-file.php?file=$1 [QSA,L]
Don’t forget to save your changes and upload the file back to your website.
Now all user requests to your media folder will be sent to a proxy script to check for authentication and redirect users to login page.
4. Adding Forms to Your WordPress Intranet with WPForms
The main goal of a company intranet is communication. BuddyPress does a great job with activity streams, comments, and private messaging.
However, sometimes you’ll need to collect information privately in a poll or survey. You’ll also need to sort and store that information for later use.
This is where WPForms comes in. It is the best WordPress form builder in the market.
Not only it allows you to easily create beautiful forms, it also saves user responses in the database. You can export responses for any form into a CSV file.
This allows you to organize form responses in spreadsheets, print them, and share among your colleagues.
Extending Your WordPress Intranet
By now you should have a perfectly capable intranet for your organization. However, as you test the platform or open it for users, you may want to add new features or make it more secure.
There are plenty of WordPress plugins that can help you do that. Here are some tools that you may want to add right away.
Sucuri – To improve WordPress security by protecting it from unauthorized access and malicious DDoS attacks.
Envira Gallery – To create beautiful photo galleries.
Google Drive Embedder – Easily embed Google Drive documents anywhere in your WordPress intranet.
That’s all for now.
We hope this article helped you create a WordPress intranet for your organization. You may also want to see our list of most useful WordPress widgets for your site.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.
The post How to Create a WordPress Intranet for Your Organization appeared first on WPBeginner.
from WPBeginner http://www.wpbeginner.com/wp-tutorials/how-to-create-a-wordpress-intranet-for-your-organization/
0 notes
Photo
Dizilerde Eleman Seçme, Ekleme, Çıkarma Sınıfı <?php class kuyruk { var $k_dizi = array(); function kuyruk($dizi){$this->k_dizi=$dizi;} function tumu(){return $this->k_dizi;} function ilk(){return reset($this->k_dizi);} function son(){return end($this->k_dizi);} function sonraki(){return next($this->k_dizi);} function onceki(){return prev($this->k_dizi);} function mevcut(){return current($this->k_dizi);} function sira($id){return $this->k_dizi[$id];} function degistir($metin){return $this->k_dizi[$this->anahtar()]=$metin;} function sil(){unset($this->k_dizi[$this->anahtar()]);return $this->mevcut();} function anahtar(){return key($this->k_dizi);} function boyut(){return sizeof($this->k_dizi);} function ilkSil(){if($this->boyut()!=0){return array_shift($this->k_dizi);}else{return false;}} function sonSil(){$c=count($this->k_dizi)-1;if($this->boyut()!=0){$s=$this->k_dizi[$c];unset($this->k_dizi[$c]);return $s;}else{return false;}} function ekle($metin){array_values($this->k_dizi);$this->k_dizi=$metin;} } $arac = array('tabanvay', 'bisiklet', 'otomobil', 'uçak'); $k=new kuyruk($arac); echo $k->sira(2)."<br>";//otomobil echo $k->ilk()."<br>";//tabanvay echo $k->sonraki()."<br>";//bisiklet echo $k->sonraki()."<br>";//otomobil echo $k->mevcut()."<br>";//otomobil echo $k->onceki()."<br>";//bisiklet echo $k->son()."<br>";//uçak echo $k->anahtar()."<br>";//3 echo $k->boyut()."<br>";//4 print_r($k->tumu());//Array ( [0] => tabanvay [1] => bisiklet [2] => otomobil [3] => uçak ) echo "<br>"; $k->degistir("at")."<br>"; print_r($k->tumu());//Array ( [0] => tabanvay [1] => bisiklet [2] => otomobil [3] => at ) echo "<br>"; $k->sil(); print_r($k->tumu());//Array ( [0] => tabanvay [1] => bisiklet [2] => otomobil ) echo "<br>"; echo $k->ilkSil()."<br>";//tabanvay print_r($k->tumu());//Array ( [0] => bisiklet [1] => otomobil ) echo "<br>"; echo $k->sonSil()."<br>";//otomobil print_r($k->tumu());//Array ( [0] => bisiklet ) echo "<br>"; $k->ekle("davul"); $k->ekle("kalem"); print_r($k->tumu());//Array ( [0] => bisiklet [1] => davul [2] => kalem ) ?>
0 notes