4th. Handling of data processing-php arrays-Zheng Achi _php Tutorial

Source: Internet
Author: User
Tags compact sorts
1. Handling of arrays:
1.1 Creation and initialization of arrays:
The 1.arrary () function creates an array, by default the 0 element is the first element of the array,
Count () and sizeof () function to get the number of data elements
2. Creating an array with variables
Compact () finds the variable name in the current symbol table and adds it to the output array, where the variable name becomes the key name and the contents of the variable become the value of the key.
Copy CodeThe code is as follows:
$num = 10;
$str = "string";
$array =array (a);
$newarray =compact ("num", "str", "array");
Print_r ($newarray);
/* Results
Array ([num]=10 [str]=>string [Array]=>array] ([0]=>1 [1]=>2] [2]=>3])
*/
?>

Extract () to convert cells in an array to variables
Copy CodeThe code is as follows:
$array =array ("Key1" =>1, "Key2" =2, "Key3" =3);
Extract ($array);
echo "$key 1 $key 2 $key 3";//Output 1 2 3
?>

3. Create an array with two arrays
Copy CodeThe code is as follows:
Array_combine (array $keys, array $values)
$a =array (' green ', ' red ', ' yellow ');
$b =array (' Volcado ', ' apple ', ' banana ');
$c =array_combine ($a, $b);
Print_r ($c);
?>

4. Creating an array of specified ranges
Range ()
5. Set up an array automatically
1.2 Key name and value operation
This section only speaks of common
。 Checks whether an array exists with a key name and value that can be used. The Array_key_exists () and In_arrary functions, isset () Check the key names in the array, and when the key name is NULL, Isset () returns false, and Array_key_exists () returns True.
。 The Array_search () function is used to check if the key value of an array exists, and no return null exists.
。 The key () function can get the name of the current cell of the array.
。 The list () function assigns the values in the array to the specified variable. is 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 populate array values and key names with a given shift
。 ARRAY_FILP () can swap the key names and values in the array, and if the interchange array has the same value, the same value is converted to the key name, and the value retains the last
。 The Array_keys () and array_values () functions can get the key names and values in the array and save them in 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 (), you can move the duplicate values in the array, return a new one, and not break the original array.
1.3 Traversal and output of arrays
1. Using the while loop to access the array
Apply the while, list (), each () function to the array traversal
2. For loop access to an array
3. Accessing an array using a Foreach Loop
Copy CodeThe code is as follows:
$color =array ("a" = "red", "blue", "white");
foreach ($color as $value)
{
echo $value. "
";//The value of the output array
}
foreach ($color as $key = $value)
{
echo $key. " = ". $value."
";//the key name and value of the output array
}
?>

Example 4.1 in the page raw text box, the user input student scores, submit the form after the output of which the score is less than 60 points, and calculate the average result after the output.
Copy CodeThe code is as follows:
echo "";
if (Isset ($_post[' BT "))//Check whether the submit button is pressed
{
$sum = 0; The total is initialized to 0.
$k = 0;
$stu =$_post[' Stu ']; Gets the value of all text boxes and assigns the array $stu
$num =count ($stu); Calculating the number of $stu elements in an array
echo "The results you have entered are:
";
foreach ($stu as $score)//Using a Foreach loop to iterate through an array $stu
{
echo $score. "
"; The output received value
$sum = $sum + $score; Calculate Total
if ($score <60)//judgment score is less than 60
{
$sco [$k]= $score; Assigns a value less than 60 to the array $sco
$k + +; Array $sco key Name index plus 1
}
}
echo "
Scores below 60 points are:
";
for ($k =0; $k echo $sco [$k]. "
";
$average = $sum/$num; Calculate Average score
echo "
The average is divided into: $average "; Output Average score
}
?>

1.4 Sorting of arrays
1. Sort in ascending order. Sort (array $array [, int $sort _flags])
Note: When sorting with mixed-type values, you need to be small because errors can occur.
Asort () can also be sorted in ascending order, which is the value of an array, but it also retains the association between the key name and the value.
Ksort () Sorts the key names of the array, and the association between the key name and the value is not changed after sorting.
2. Sort in descending order. Rsort (), Arsort (), Krsort ()
3. Sorting of multidimensional arrays.
4. Reorder the arrays.
。 The shuffle () function. The function arranges the array in random order and deletes the original key name
。 The Array_reverse () function. Sorts an array in reverse order.
5. Natural sorting
。 Natsort (). Sensitive to case
1.5 Other operations
1. Merging arrays
Array_merge ($array 1, $array 2). After merging, the array of one-dimensional numbers is returned as a unit. Array_merge_recusive () can be merged with an array under the current structure.
2. Stack operation of the array.
Out of Stack: Array_pop ($arr);
Into the stack: Array_push ($arr, Var);
3. Get the current cell of the array
1. The current () function is able to get the value of the cell to which the pointer in the array is pointing, but does not move the inner pointer of the array.
2. Next ($arr), move the pointer to the next cell.
3. End ($arr) moves the pointer to the trailer.
4. Array calculations
Count (), sizeof () computes the number of elements in the array
The Array_count_values () function calculates the number of occurrences of a value in an array
Example: 4.2 Processing Tabular data
Receive input from the students to learn things, names, scores and other information, the received information into the array and in accordance with the results in ascending order. After that, the output is in table.
Copy CodeThe code is as follows:


Note: The value of the study number cannot be repeated


if (Isset ($_post[' bt_stu '))//Determine if the button is pressed
{
$XH =$_post[' XH ']; Receive the value of all the numbers in the array $xh
$XM =$_post[' XM ']; Receive all name values in array $xm
$CJ =$_post[' CJ ']; Receive the value of all scores in the array $CJ
Array_multisort ($CJ, $XH, $XM); Sort the above three arrays, $CJ as the primary array
for ($i =0; $i $sum [$i]=array ($XH [$i], $XM [$i], $CJ [$i]); The values of three arrays are composed of a two-dimensional array $sum
echo "After sorting the results table as follows:";
The header of the table
echo "






"; foreach ($sum as $value)//Use the Foreach loop to iterate through the array $sum {list ($stu _number, $stu _name, $stu _score) = $value;//Use List () The function assigns the value in the array to the variable//output table content echo " "; } echo "
School Number Name Results
$stu _number $stu _name $stu _score

"; Tail of Table
Reset ($sum); Resetting a pointer to an $sum array
while (list ($key, $value) =each ($sum))//use while loop to iterate through an array
{
List ($stu _number, $stu _name, $stu _score) = $value;
if ($stu _number== "081101")//query whether there is a value of 081101 for the study number
{
echo " ";
Echo $stu _number. The name is: ". $stu _name.", "; The
Echo "score is:". $stu _score;
break;//Find End Loop
}
}
}
?>

ht tp://www.bkjia.com/phpjc/323896.html www.bkjia.com true http:// www.bkjia.com/PHPjc/323896.html techarticle 1. Array Processing: 1.1 Array creation and initialization: the 1.arrary () function creates an array, by default the 0 element is the first element of the array, and the count () and sizeof () function gets the data element's ...

  • 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.