4th Chapter Data Processing-php array processing-Zheng Achi

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

Extract () Converts a cell in an array to a variable
Copy CodeThe code is as follows:
<?php
$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 using two arrays
Copy CodeThe code is as follows:
Array_combine (array $keys, array $values)
<?php
$a =array (' green ', ' red ', ' yellow ');
$b =array (' Volcado ', ' apple ', ' banana ');
$c =array_combine ($a, $b);
Print_r ($c);
?>

4. Set up the specified range array
Range ()
5. Automatically build arrays
1.2 Operation of key names and values
This section only talks about the usual
。 Check that the array has a key name and value to use. The Array_key_exists () and In_arrary functions, isset () Check the key names in the array, and when the key is null, Isset () returns false, and Array_key_exists () returns True.
。 The Array_search () function checks for the existence of the key value of the array, and does not exist to return null.
。 The key () function can get the keys of the current cell of the array.
。 The list () function to assign the values in the array to the specified variable. is useful in array traversal.
<?php
$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 the values and key names of the array with the given duty
。 ARRAY_FILP () can swap the key names and values in the array, and if the Exchange array has the same value, the same value is converted to the key, and the value remains the last
。 The Array_keys () and array_values () functions can take the key names and values from 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 an array and replaces them with other values.
。 Array_unique (), you can move a duplicate value in an array, return a new one, and do not break the original array.
Traversal and output of 1.3 arrays
1. Using a while loop to access the array
Using the while, List (), each () function to traverse the array
2. For loop Access array
3. Iterate through the array using foreach
Copy CodeThe code is as follows:
<?php
$color =array ("A" => "Red", "blue", "white");
foreach ($color as $value)
{
echo $value. " <br>//Output array value
}
foreach ($color as $key => $value)
{
echo $key. " => ". $value." <br>//Output array's key name and value
}
?>

Example 4.1 in the page raw text box, the user input student scores, submit the form after the output score is less than 60 points, and calculate the average results after output.
Copy CodeThe code is as follows:
<?php
echo "<form method=post>"; Create a new form
For ($i =1 $i <6; $i + +)//looping to generate text boxes
{
The name of the text box is the array name
echo "Student". $i. " Achievements: <input type=text name= ' stu[] ' ><br> ';
}
echo "<input type=submit name=bt value= ' submit ' >"; Submit button
echo "</form>";
if (Isset ($_post[' BT '))//Check whether the submit button is pressed
{
$sum = 0; Total score initialized to 0
$k = 0;
$stu =$_post[' Stu ']; Gets the value of all text boxes and assigns the array $stu
$num =count ($stu); Count the number of $STU elements in an array
echo "You have entered a score of:<br>";
foreach ($stu as $score)//Using a Foreach loop to iterate through an array $stu
{
echo $score. " <br> "; Value received by output
$sum = $sum + $score; Calculate the total score
if ($score <60)//judgment score less than 60
{
$sco [$k]= $score; Assigns a value of less than 60 to an array $sco
$k + +; The index of the key name of the array $sco plus 1
}
}
echo "<br> below 60 score has:<br>";
For ($k =0 $k <count ($sco); $k + +)//use for loop output $sco array
echo $sco [$k]. " <br> ";
$average = $sum/$num; Calculate Average score
echo "<br> average divided into: $average"; Output Average score
}
?>

1.4 Ordering of arrays
1. Ascending sort. Sort (array $array [, int $sort _flags])
Note: When sorting with mixed type values, you should be small, because an error may occur.
Asort () can also be sorted in ascending order, which is sorted by the value of an array, but its sorted arrays also hold the association between the key name and the value.
Ksort () The key name of the array is sorted, and the association between the key name and the value is not changed after sorting.
2. Descending sort. Rsort (), Arsort (), Krsort ()
3. Sorting of multidimensional arrays.
4. Reordering of arrays.
。 Shuffle () function. The function arranges the array in a random order and deletes the original key name
。 Array_reverse () function. Sorts an array in reverse order.
5. Natural order
。 Natsort (). Case sensitive
1.5 Other operations
1. Merging arrays
Array_merge ($array 1, $array 2). After merging, the array after one dimension is returned as a unit. Array_merge_recusive () can merge arrays under existing array structures.
2. Stack operation of Array.
Out stack: Array_pop ($arr);
Into the stack: Array_push ($arr, Var);
3. Get the current cell of the array
1. The current () function gets the value of the cell that the internal pointer points to, but does not move the internal pointer to the array.
2. Next ($arr), move the pointer to the next cell.
3. End ($arr) moves the pointer to the tail.
4. Array calculation
Count (), sizeof () calculates the number of elements in an array
The Array_count_values () function calculates the number of occurrences of a value in an array
Example: 4.2 Processing Tabular data
To receive information about students ' learning, names, grades and so on, the received information is stored in an array and sorted in ascending order. And then the table output.
Copy CodeThe code is as follows:
<form NAME=FR1 method=post>
<table Align=center border=1 >
<tr>
<td><div align=center> No. </div></td>
<td><div align=center> name </div></td>
<td><div align=center> score </div></td>
</tr>
<?php
For ($i =0 $i <5; $i + +)//Looping text boxes to generate tables
{?>
<tr>
<td><input type=text name= "xh[]" ></td>
<td><input type=text name= "xm[]" ></td>
<td><input type=text name= "cj[]" ></td>
</tr>
?? >
&LT;TR&GT;&LT;TD align = "center" colspan= "3" >
<input type= "Submit" Name= "Bt_stu" value= "submitted" ></td></tr>
</table>
</form>
<center><font size=3 color= "Red" >
Note: The value of the school number cannot be repeated </font></center><br>
<!--above is input form-->
<?php
if (Isset ($_post[' bt_stu '))//Judge Button is pressed
{
$XH =$_post[' XH ']; Receive the value of all the school numbers in an array $xh
$XM =$_post[' XM ']; Receive the value of all names in an array $xm
$CJ =$_post[' CJ ']; The value of receiving all grades is stored in an array $CJ
Array_multisort ($CJ, $XH, $XM); Sorts the above three arrays, $CJ as the primary array
for ($i =0; $i <count ($XH); $i + +)
$sum [$i]=array ($XH [$i], $XM [$i], $CJ [$i]); Make a two-dimensional array of the values of three arrays $sum
echo "<div align=center> after sorting the score table as follows:</div>";
The header of the table
echo "<table align=center border=2><tr><td> </td><td> name </td><td> Results < /td></tr> ";
foreach ($sum as $value)//Using a Foreach loop to iterate through an array $sum
{
List ($stu _number, $stu _name, $stu _score) = $value; Use the list () function to assign values in an array to a variable
Output table Contents
echo "<tr><td> $stu _number</td><td> $stu _name</td><td> $stu _score</td> </tr> ";
}
echo "</table><br>"; Table Tail
Reset ($sum); Reset pointer to $sum array
while (list ($key, $value) =each ($sum)///use while loop to traverse an array
{
List ($stu _number, $stu _name, $stu _score) = $value;
if ($stu _number== "081101")//query If there is a value of number 081101
{
echo "<center><font size=4 color=red>";
echo $stu _number. " The name is: ". $stu _name.", ";
echo "Score:". $stu _score;
Break End Loop If 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.