Chapter 4 data processing-php Array Processing-zheng AQI _ php entry _ script house

Source: Internet
Author: User
Chapter 4 data processing-php Array Processing-zheng AQI, a friend of php learning must pay attention to it. php arrays are commonly used.

Chapter 4 data processing-php Array Processing-zheng AQI, a friend of php learning must pay attention to it. php arrays are commonly used.

1. Array Processing:
1.1 create and initialize an array:
1. The arrary () function creates an array. By default, element 0 is the first element of the array,
The count () and sizeof () functions obtain the number of data elements.
2. Use variables to create an array
Compact () searches for the variable name in the current symbol table and adds it to the output array. The variable name becomes the key name and the variable content becomes the key value.
The Code is as follows:
$ Num = 10;
$ Str = "string ";
$ Array = array (1, 2, 3 );
$ Newarray = compact ("num", "str", "array ");
Print_r ($ newarray );
/* Result
Array ([num] = 10 [str] => string [array] => array ([0] => 1 [1] => 2 [2] => 3 ))
*/
?>

Extract () converts cells in the array into variables.
The Code is as follows:
$ Array = array ("key1" => 1, "key2" = 2, "key3" = 3 );
Extract ($ array );
Echo "$ key1 $ key2 $ key3"; // output 1 2 3
?>

3. Create an Array Using Two Arrays
The Code is as follows:
Array_combine (array $ keys, array $ values)
$ A = array ('green', 'red', 'yellow ');
$ B = array ('volcado', 'apple', 'bana ');
$ C = array_combine ($ a, $ B );
Print_r ($ c );
?>

4. Create a specified range array
Range ()
5. automatically create an array
1.2 key name and value operations
This section only describes common
. Check whether a key name and value exist in the array. Array_key_exists () and in_arrary functions. isset () checks the key names in the array. If the key name is NULL, isset () returns false, while array_key_exists () returns true.
. The array_search () function is used to check whether the key value of the array exists. If no key exists, NULL is returned.
. The key () function can obtain the key name of the current cell of the array.
. List () function, which assigns the value of the array to the specified variable. It is very useful in array traversal.
$ Arr = array ("red", "blue", "White ");
List ($ red, $ blue, $ white) = $ arr;
Echo $ red; // red
Echo $ blue; // blue
Echo $ white; // white
. Array_fill () and array_fill_keys () can be filled with the value and key names of the array with the given duty schedule.
. Array_filp () can exchange the key names and values in the array. In addition, if the exchanged array has the same value, the same value is converted to the key name, and the value is retained to the last one.
. The array_keys () and array_values () functions can obtain the key names and values in the array and save them to a new array.
. Array_splice (arry $ input, int $ offset [, int $ length [, array $ replacement]) deletes one or more cells in the array and replaces them with other values.
. Array_unique () can be used to remove duplicate values from the array and return a new array without damaging the original array.
1.3 array traversal and Output
1. Use the while loop to access the Array
Apply the while, list (), and each () functions to traverse arrays.
2. for Loop access Array
3. Use foreach to access the array cyclically
The Code is as follows:
$ Color = array ("a" => "red", "blue", "white ");
Foreach ($ color as $ value)
{
Echo $ value ."
"; // Output array value
}
Foreach ($ color as $ key => $ value)
{
Echo $ key. "=>". $ value ."
"; // Key name and value of the output Array
}
?>

In Example 4.1, a text box is generated on the page. The user enters the score of the student. after submitting the form, the score is less than 60 and the average score is calculated.
The Code is as follows:
Echo "";
If (isset ($ _ POST ['bt ']) // check whether the submit button is pressed
{
$ Sum = 0; // The total score is initialized to 0.
$ K = 0;
$ Stu = $ _ POST ['stu']; // obtain the values of all text boxes and assign the array $ stu
$ Num = count ($ stu); // calculates the number of elements in the array $ stu.
Echo "your input scores include:
";
Foreach ($ stu as $ score) // use foreach loop to traverse the array $ stu
{
Echo $ score ."
"; // Output the received value
$ Sum = $ sum + $ score; // calculate the total score
If ($ score <60) // determines if the score is less than 60
{
$ Sco [$ k] = $ score; // assign a score less than 60 to the array $ sco
$ K ++; // array $ sco key name index plus 1
}
}
Echo"
Scores below 60:
";
For ($ k = 0; $ k Echo $ sco [$ k]."
";
$ Average = $ sum/$ num; // calculate the average score
Echo"
Average score: $ average "; // average output score
}
?>

1.4 sort Arrays
1. Sort in ascending order. Sort (array $ array [, int $ sort_flags])
Note: the sorting of values containing mixed types should be minimized because errors may occur.
Asort () can also be sorted in ascending order to sort the values of the array, but the sorted array still maintains the association between key names and values.
Ksort () sorts the key names of the array. After sorting, the association between the key names and values remains unchanged.
2. Sort in descending order. Rsort (), arsort (), krsort ()
3. Multi-dimensional array sorting.
4. Sort the array again.
. Shuffle () is used to sort arrays in random order and delete the original key names.
. Array_reverse () function. sorts an array in reverse order.
5. Natural sorting
. Natsort (). Case Sensitive
1.5 Other operations
1. Merge Arrays
Array_merge ($ array1, $ array2). After merging, the array after one-dimensional number is returned as a unit. Array_merge_recusive () can merge arrays while maintaining the existing array structure.
2. Stack operations of arrays.
Output Stack: array_pop ($ arr );
Inbound Stack: array_push ($ arr, var );
3. Get the current cell of the array
1. The current () function can obtain the value of the unit pointed to by the internal pointer of the array, but does not move the internal pointer of the array.
2. next ($ arr), move the pointer to the next unit.
3. end ($ arr) moves the pointer to the end.
4. array Calculation
Count () and sizeof () calculate the number of elements in the array
The array_count_values () function can calculate the number of occurrences of a value in the array.
Example: 4.2 Process Table Data
Receives student information, such as student information, name, and score input by the user, stores the received information in an array, and sorts the received information in ascending order. And then output in a table ..
The Code is as follows:


Note: The student ID value cannot be repeated.


If (isset ($ _ POST ['bt _ stu']) // determines whether the button is pressed.
{
$ XH = $ _ POST ['xh']; // receives the values of all student IDs and saves them to the array $ XH
$ XM = $ _ POST ['xm ']; // receives the values of all names in the array $ XM
$ CJ = $ _ POST ['cj ']; // receives all score values and saves them to the array $ CJ
Array_multisort ($ CJ, $ XH, $ XM); // sorts the preceding three arrays. $ CJ is the primary array.
For ($ I = 0; $ I $ Sum [$ I] = array ($ XH [$ I], $ XM [$ I], $ CJ [$ I]); // combine the values of the three arrays into a two-dimensional array $ sum
Echo"

The sorted orders table is as follows:

";
// Table Header
Echo"






";Foreach ($ sum as $ value) // use foreach loop to traverse the array $ sum{List ($ stu_number, $ stu_name, $ stu_score) = $ value; // use the list () function to assign values in the array to the variable// Output table contentEcho" ";}Echo"
Student ID Name Score
$ Stu_number $ Stu_name $ Stu_score

"; // End of the table
Reset ($ sum); // reset the pointer to the $ sum Array
While (list ($ key, $ value) = each ($ sum) // use the while loop to traverse the Array
{
List ($ stu_number, $ stu_name, $ stu_score) = $ value;
If ($ stu_number = "081101") // you can check whether the student ID is 081101.
{
Echo" ";
Echo $ stu_number. "name:". $ stu_name .",";
Echo "score:". $ stu_score;
Break; // The loop ends when it is found.
}
}
}
?>

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.