第4章 数据处理-php数组的处理-郑阿奇_php入门_脚本之家
第4章 数据处理-php数组的处理-郑阿奇,学习php的朋友一定要重视下,php数组是比较常用的。
1.数组的处理:
1.1 数组的创建和初始化:
1.arrary()函数创建数组,默认情况下0元素是数组的第一个元素,
count()和sizeof()函数获得数据元素的个数
2.使用变量建立数组
compact()在当前的符号表中查找该变量名并将它添加到输出的数组中,变量名成为键名而变量的内容成为该键的值.
代码如下:
$num=10;
$str="string";
$array=array(1,2,3);
$newarray=compact("num","str","array");
print_r($newarray);
/*结果
array([num]=10 [str]=>string [array]=>array([0]=>1 [1]=>2 [2]=>3))
*/
?>
extract() 将数组中的单元转为变量
代码如下:
$array=array("key1"=>1,"key2"=2,"key3"=3);
extract($array);
echo "$key1 $key2 $key3";//输出1 2 3
?>
3.使用两个数组创建一个数组
代码如下:
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.建立指定范围数组
range()
5.自动建立数组
1.2 键名和值的操作
本小节只讲常用的
。检查数组是否存在某个键名和值可以使用。array_key_exists()和in_arrary函数,isset()检查数组中的键名,当键名为NULL时,isset()返回 false,而array_key_exists()返回true.
。array_search()函数用于检查数组的键值是否存在,不存在返回NULL。
。key()函数可以取得数组当前单元的键名.
。list()函数,将数组中值赋给指定的变量。在数组遍历中非常有用。
$arr=array("红色","蓝色","白色");
list($red,$blue,$white)=$arr;
echo $red; //红色
echo $blue; //蓝色
echo $white; // 白色
。array_fill()和array_fill_keys()可以用给定的值班填充数组的值和键名
。array_filp()可以交换数组中的键名和值,另外如果交换数组中有相同的值,则相同的值转换为键名后,值保留最后一个
。array_keys()和array_values()函数可以取得数组中的键名和值,并保存到一个新的数组中。
。array_splice(arry $input,int $offset[,int $length[,array $replacement]])将数组中的一个或多个单元删除并用其它值代替。
。array_unique(),可以移除数组中的重复的值,返回一个新数组,并不会破坏原有的数组。
1.3 数组的遍历与输出
1.使用while 循环访问数组
应用while、list()、each()函数对数组遍历
2. for循环访问数组
3.使用foreach循环访问数组
代码如下:
$color=array("a"=>"red","blue","white");
foreach($color as $value)
{
echo $value."
";//输出数组的值
}
foreach($color as $key=>$value)
{
echo $key."=>".$value."
";//输出数组的键名和值
}
?>
例4.1 在页面生成品个文本框,用户输入学生成绩,提交表单后输出其中分数小于60分的值,并计算平均成绩后输出。
代码如下:
echo "";
if(isset($_POST['bt'])) //检查提交按钮是否按下
{
$sum=0; //总成绩初始化为0
$k=0;
$stu=$_POST['stu']; //取得所有文本框的值并赋予数组$stu
$num=count($stu); //计算数组$stu元素个数
echo "您输入的成绩有:
";
foreach($stu as $score) //使用foreach循环遍历数组$stu
{
echo $score."
"; //输出接收的值
$sum=$sum+$score; //计算总成绩
if($score{
$sco[$k]=$score; //将分数小于60的值赋给数组$sco
$k++; //数组$sco的键名索引加1
}
}
echo "
低于60分的成绩有:
";
for($k=0;$k
";
$average=$sum/$num; //计算平均成绩
echo "
平均分为:$average"; //输出平均成绩
}
?>
1.4 数组的排序
1.升序排序 。sort(array $array[,int $sort_flags])
注意:在对含有混合类型值的排序时要小尽,因为可能会产生错误。
asort()也可升序排序,是对数组的值进行排序,但它排序后的数组还保持键名和值之间的关联。
Ksort()对数组的键名排序,排序后键名和值之间的关联不改变。
2.降序排序。 rsort()、arsort()、krsort()
3.多维数组的排序。
4.对数组重新排序。
。shuffle()函数.作用将数组用随机的顺序排列,并删除原有的键名
。array_reverse()函数.将一个数组按相反顺序排序.
5.自然排序
。natsort().对大小写敏感
1.5其它操作
1. 合并数组
array_merge($array1,$array2).合并后将一维数以后的数组都当做一个单元返回。array_merge_recusive()可以在保持现有数组结构下对数组进行合并。
2. 数组的栈操作.
出栈: array_pop($arr);
入栈: array_push($arr,var);
3.取得数组当前单元
1. current()函数能够获取数组内部指针指向的单元的值,但不移动数组的内部指针。
2. next($arr),将指针移到下一个单元。
3. end($arr)将指针移到尾部。
4.数组计算
count()、sizeof()计算数组中的元素个数
array_count_values()函数可以计算数组中的一个值出现的次数
例:4.2 处理表格数据
接收用户输入的学生学事情、姓名、成绩等信息,将接收到的信息存入数组并按照成绩升序排序。之后再以表格输出。.
代码如下:
注意:学号值不能重复
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
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; //找到则结束循环
}
}
}
?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values takes a relatively long time.

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

The PHP array merging and deduplication algorithm provides a parallel solution, dividing the original array into small blocks for parallel processing, and the main process merges the results of the blocks to deduplicate. Algorithmic steps: Split the original array into equally allocated small blocks. Process each block for deduplication in parallel. Merge block results and deduplicate again.

PHP's array_group() function can be used to group an array by a specified key to find duplicate elements. This function works through the following steps: Use key_callback to specify the grouping key. Optionally use value_callback to determine grouping values. Count grouped elements and identify duplicates. Therefore, the array_group() function is very useful for finding and processing duplicate elements.
