Chapter 4 Data Processing-PHP Array Processing-Zheng Aqi_PHP Tutorial

WBOY
Release: 2016-07-21 15:26:34
Original
1286 people have browsed it

1. Processing of arrays:
1.1 Creation and initialization of arrays:
1. The array() function creates an array. By default, element 0 is the first element of the array.
count() and sizeof( ) function to obtain the number of data elements
2. Create an array using variables
compact() finds 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 The content becomes the value of the key.

Copy code 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() Convert the cells in the array into variables
Copy code The code is as follows:

$array=array("key1"=>1,"key2"=2, "key3"=3);
extract($array);
echo "$key1 $key2 $key3";//Output 1 2 3
?>

3. Use two arrays to create an array
Copy the code The 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. Create a specified range array
range( )
5. Automatically create an array
1.2 Operations on key names and values ​​
This section only talks about commonly used ones
. Checks whether a certain key and value exist in an array and can be used. Array_key_exists() and in_arrary functions, isset() checks the key name in the array. When 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 it does not exist, NULL is returned.
. The key() function can obtain the key name of the current unit of the array.
. The list() function assigns the values ​​in the array to the specified variable. 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 fill the values ​​and keys of an array with the given values ​​
. array_filp() can exchange the key names and values ​​in the array. In addition, if there are the same values ​​in the exchange array, after the same values ​​are converted into key names, the last
of the value will be retained. 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 remove duplicate values ​​from an array and return a new array without destroying the original array.
1.3 Array traversal and output
1. Use while loop to access the array
Apply while, list(), and each() functions to traverse the array
2. for loop to access the array
3. Use foreach to loop through the array
Copy code The code is as follows:

$color=array(" a"=>"red","blue","white");
foreach($color as $value)
{
echo $value."
";//output Value of array
}
foreach($color as $key=>$value)
{
echo $key."=>".$value."
"; //Output the key name and value of the array
}
?>

Example 4.1 Generate a text box on the page, the user enters the student's score, and after submitting the form, output the score less than 60 The score value is calculated and output after calculating the average score.
Copy code The code is as follows:

echo "
"; //Create a new form
for($i=1;$i<6;$i++) //Loop generation Text box
{
//The name of the text box is the array name
echo "Student".$i."'s score:< br>";
}
echo ""; //Submit button
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']; //Get the values ​​of all text boxes and assign them to the array $stu
$num=count($stu); //Calculate the number of elements in the array $stu
echo "The scores you entered are:
";
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) //Judge the situation when the score is less than 60
{
$sco [$k]=$score; //Assign the value with a score less than 60 to the array $sco
$k++; //Add 1 to the key index of the array $sco
}
}
echo "
The scores below 60 points are:
";
for($k=0;$kecho $sco[$k]."
";
$average=$sum/$num; //Calculate the average score
echo "
Average score: $average "; //Output average score
}
?>

1.4 Sorting of arrays
1. Sort in ascending order. sort(array $array[,int $sort_flags])
Note: Be careful when sorting values ​​containing mixed types, as errors may occur.
asort() can also be sorted in ascending order, which sorts the values ​​of the array, but the sorted array still maintains the association between key names and values.
Ksort() sorts the keys of the array. The relationship between the keys and values ​​does not change after sorting.
2. Sort in descending order. rsort(), arsort(), krsort()
3. Sorting of multi-dimensional arrays.
4. Reorder the array.
. shuffle() function. Its function is to arrange the array in random order and delete the original key name
. array_reverse() function. Sort an array in reverse order.
5. Natural sorting
. natsort(). Case sensitive
1.5 Other operations
1. Merge arrays
array_merge($array1,$array2). After merging, all arrays after one dimension will be returned as one unit. array_merge_recusive() can merge arrays while maintaining the existing array structure.
2. Stack operation of array.
Pop: array_pop($arr);
Push: array_push($arr,var);
3. Get the current unit of the array
1. The current() function can obtain the value of the cell pointed to by the internal pointer of the array, but does not move the internal pointer of the array.
2. next($arr), moves 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
array_count_values() function can count the number of times a value appears in the array
Example: 4.2 Processing table data
Receive information such as students’ academic affairs, names, grades and other information input by the user, store the received information into an array and sort it in ascending order of grades. Then output it as a table. .
Copy code The code is as follows:








for($i=0;$i<5;$i++) //循环生成表格的文本框
{?>







学号
姓名
成绩




注意:学号值不能重复



if(isset($_POST['bt_stu'])) //判断按钮是否按下
{
$XH=$_POST['XH']; //接收所有学号的值存入数组$XH
$XM=$_POST['XM']; //接收所有姓名的值存入数组$XM
$CJ=$_POST['CJ']; //接收所有成绩的值存入数组$CJ
array_multisort($CJ,$XH,$XM); //对以上三个数组排序,$CJ为首要数组
for($i=0;$i$sum[$i]=array($XH[$i],$XM[$i],$CJ[$i]); //将三个数组的值组成一个二维数组$sum
echo "
排序后成绩表如下:
";
//表格的首部
echo "";
foreach($sum as $value) //使用foreach循环遍历数组$sum
{
list($stu_number,$stu_name,$stu_score)=$value; //使用list()函数将数组中的值赋给变量
//输出表格内容
echo "";
}
echo "
学号姓名成绩
$stu_number$stu_name$stu_score

"; //表格尾部
reset($sum); //重置$sum数组的指针
while(list($key,$value)=each($sum)) //使用while循环遍历数组
{
list($stu_number,$stu_name,$stu_score)=$value;
if($stu_number=="081101") //查询是否有学号为081101的值
{
echo "
";
echo $stu_number."的姓名为:".$stu_name.",";
echo "成绩为:".$stu_score;
break; //找到则结束循环
}
}
}
?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/323896.htmlTechArticle1.数组的处理: 1.1 数组的创建和初始化: 1.arrary()函数创建数组,默认情况下0元素是数组的第一个元素, count()和sizeof()函数获得数据元素的...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template