PHP-PHP source code

Source: Internet
Author: User
Php's associated data usage and some tips for associating arrays, including adding, deleting, editing, traversing, exchanging keys and values, sorting, querying, and other associated array instances. Php's associated data usage and some tips for associating arrays, including adding, deleting, editing, traversing, exchanging keys and values, sorting, querying, and other associated array instances.

Script ec (2); script

1. Add array elements
PHP is a weak type language, which means you do not need to declare an array and its size. On the contrary, you can declare and fill the array at the same time.

The Code is as follows:
$ Capitals = array (
'Babama' => 'mongomery ',
'Apache' => 'juneau ',
'Arizona '=> 'phoenix'
);

The additional array elements can be appended as follows:

$ Capitals ['arkansas '] = 'little Rock'; if you are processing a numeric index array, you may want to use the frontend and append elements of the display named function, such as array_push () and array_unshift () functions, but these functions cannot be used to associate arrays.

2. Delete array elements
To delete an element from an array, use the unset () function, for example:

The Code is as follows:
Unset ($ capitals ['california ']);

When using a numeric index array, there are more ways to delete array elements. You can use the array_shift () and array_pop () functions to delete an element from the beginning and end of the array.

3. Exchange Keys and values
Suppose you want to create a new array named $ states, use the state government as the index, and use the state name as the associated value. The array_flip () function can easily complete this task.

The Code is as follows:
$ Capitals = array (
'Babama' => 'mongomery ',
'Apache' => 'juneau ',
'Arizona '=> 'phoenix'
);
$ States = array_flip ($ capitals );
// $ States = array (
// 'Mongomery' => string 'abama ',
// 'Juneau '=> string 'alaska ',
// 'Phoenix '=> string 'arizona'
//);

4. Merge Arrays
If the preceding array is used by a Web-based "FlashCard" service, you can use array_merge () to test students' knowledge about the state capitals in the United States () functions merge arrays containing states and capitals.

The Code is as follows:


$ StateCapitals = array (
'Babama' => 'mongomery ',
'Apache' => 'juneau ',
'Arizona '=> 'phoenix'
);
$ CountryCapitals = array (
'Australia '=> 'canonical ',
'Austria' => 'Vienna ',
'Algera' => 'algiers'
);
$ Capitals = array_merge ($ stateCapitals, $ countryCapitals );

5. Edit the array value
If the data in the array contains case-insensitive errors, you can use the array_map () function to apply a callback to each array element before inserting the data into the database.

The Code is as follows:


Function capitalize ($ element)
{
$ Element = strtolower ($ element );
Return ucwords ($ element );
}
$ Capitals = array (
'Babama' => 'mongomery ',
'Apache' => 'juneau ',
'Arizona '=> 'phoenix'
);
$ Capitals = array_map ("capitalize", $ capitals );

6. Sort arrays by pressing the buttons
The flash card program uses various sorting methods. For example, you can use the ksort () function to sort the associated arrays in alphabetical order.

The Code is as follows:

$ Capitals = array (
'Arizona '=> 'phoenix ',
'Apache' => 'juneau ',
'Babama' => 'mongomery'
);
Ksort ($ capitals );

Because the array is passed to the ksort () function through parameters, it means that you no longer need to assign the sorting result to another variable.

7. random array sorting
Another random sorting technique is involved in the flash card program. In this case, you need to use the shuffle () function to implement random sorting of array projects.

The Code is as follows:

$ Capitals = array (
'Arizona '=> 'phoenix ',
'Apache' => 'juneau ',
'Babama' => 'mongomery'
);
Shuffle ($ capitals );

If you do not need to disrupt the array order and want to randomly select a value, use the array_rand () function.

8. Check whether the key and value exist.
You can use the in_array () function to determine whether an array element exists.

The Code is as follows:

$ Capitals = array (
'Arizona '=> 'phoenix ',
'Apache' => 'juneau ',
'Babama' => 'mongomery'
);
If (in_array ("Juneau", $ capitals ))
{
Echo "Exists! ";
} Else {
Echo "Does not exist! ";
}

Few people know that this function can also determine whether an array key exists. At this point, it functions the same as the array_key_exists () function.

The Code is as follows:
$ Capitals = array (
'Arizona '=> 'phoenix ',
'Apache' => 'juneau ',
'Babama' => 'mongomery'
);
If (array_key_exists ("Alaska", $ capitals ))
{
Echo "Key exists! ";
} Else {
Echo "Key does not exist! ";
}

9. Search for Arrays
You may want to search for Array resources, so that you can easily search associated States using a specific state government. You can use the array_search () function to search for arrays.

The Code is as follows:


$ Capitals = array (
'Arizona '=> 'phoenix ',
'Apache' => 'juneau ',
'Babama' => 'mongomery'
);
$ State = array_search ('juneau ', $ capitals );
// $ State = 'alaska'

10. Standard PHP Library
The Standard PHP Library (SPL) provides developers with many data structures, iterators, interfaces, exceptions, and other functions not available in the previous PHP language, these functions can be used to traverse arrays through object-oriented syntax.

The Code is as follows:


$ Capitals = array (
'Arizona '=> 'phoenix ',
'Apache' => 'juneau ',
'Babama' => 'mongomery'
);
$ ArrayObject = new ArrayObject ($ capitals );
Foreach ($ arrayObject as $ state => $ capital)
{
Printf ("The capital of % s is % s
", $ State, $ capital );
}
// The capital of Arizona is Phoenix
// The capital of Alaska is Juneau
// The capital of Alabama is Montgomery

Three methods to traverse correlated Arrays:

Foreach

The Code is as follows:
$ Sports = array (
'Football' => 'good ',
'Canonicalization' => 'very well ',
'Running' => 'not good'
);

Foreach ($ sports as $ key => $ value ){
Echo $ key. ":". $ value ."
";
}
?>

Program running result:

Football: good

Faster Ming: very well

Running: not good


Each

The Code is as follows:

$ Sports = array (
'Football' => 'good ',
'Canonicalization' => 'very well ',
'Running' => 'not good'
);

While ($ elem = each ($ sports )){
Echo $ elem ['key']. ":". $ elem ['value']."
";
}
?>

Program running result:

Football: good
Faster Ming: very well
Running: not good

List & each

The Code is as follows:

$ Sports = array (
'Football' => 'good ',
'Canonicalization' => 'very well ',
'Running' => 'not good'
);

While (list ($ key, $ value) = each ($ sports )){
Echo $ key. ":". $ value ."
";
}
?>

Program running result:

Football: good
Faster Ming: very well
Running: not good


Hash Table = Hash Table


There is a list of user names, storing 10000 user names without repeated items;
There is also a blacklist list that stores 2000 user names in the same format as the user name list;
Now, you need to delete the user name in the blacklist from the user name list, which must be processed as quickly as possible.

This problem is a small-scale processing capacity. If it is practical, two tables may be very large, for example, there are 0.2 billion records.

The method I first came up with was to create a nested loop, with M records in the User table and N records in the blacklist list. Then, the number of cycles is M * N!
PHP code:

The Code is as follows:
Foreach ($ arrayM as $ keyM => $ nameM ){
Foreach ($ arrayN as $ nameN ){
If ($ nameM = $ nameN ){
// This row has been executed M * N times!
Unset ($ arrayM [$ keyM]);
}
}
}
Return $ arrayM;
?>

Another method is to use array indexes.

PHP is a weak type language and does not have strict variable type restrictions as C does. C language array, each element type must be consistent, and the index starts from 0.
PHP arrays, which can be indexed by strings, are also called associated arrays.
Array indexes have a natural limit that they do not repeat and do not need to be searched during access. They can be directly located.

Or the problem we just mentioned, we adopt another method.

Organize the User Name of the blacklist list into an array. The index of the array is the user name.

Then, when traversing the user list, you only need to use isset to query whether the user name exists.

PHP code:

The Code is as follows:

$ ArrayHash = array ();
Foreach ($ arrayN as $ nameN ){
// This row has been executed N times.
$ ArrayHash [$ nameN] = 1;
}

Foreach ($ arrayM as $ keyM => $ nameM ){
If (isset ($ arrayHash [$ nameM]) {
// This row has been executed M times!
Unset ($ arrayM [$ keyM]);
}
}
Return $ arrayM;
?>

We can see that the number of Optimized Code loops is M + N.

If both M and N are 10000, the cycle is 0.1 billion times before optimization. After optimization, only 20000 times are cyclically reduced, which is 5000 times worse!
If the second program takes 1 second, the first program takes nearly one and a half hours.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.