PHP的数组应用基础(五)

黄舟
Release: 2023-03-03 21:20:01
Original
1321 people have browsed it

1.foreach循环语句遍历二维数组。这是二维数组的foreach遍历。
$erwei_arr = array(
array(“xiaoliu”,”123456″,”小刘”,”男”,29,”系统分析师”) ,
array(“xiaozeng”,”123456″,”小曾”,”男”,23,”Web工程师”) ,
array(“xiaochen”,”123456″,”小陈”,”男”,29,”Java工程师”)
); //声明索引二维数组

$html = “

”; //定义字符串$html,字符串的内容是表格的
标签
foreach($erwei_arr as $field){
$html .= “”; //用字符串运算符将$html原来的值与””连接成新的字符串,下同
foreach($field as $value){
$html .= “”;
}
$html .= “”;
}
$html .= “
”.$value.”
”;

echo $html;

结果是

PHP对表格的操作就这么出来了。呵呵。

2.常用数组处理函数

数组处理函数也比较重要,比如随机函数,排序函数等。大致有:

索引/值操作函数

in_array()检查数组中是否存在某个值、array_search()在数组中搜索给定的值,如果成功则返回相应的键名、array_key_exists()检查给定的键名是否存在于数组中

数组排序函数

sort()对数组按照值进行升序,重新枚举数组,rsort()为降序,与之相反。asort()对数组按照值进行升序,保持索引与值的关联,arsort()与之相反。ksort()对数组按照键名进行升序,保持索引与值的关联,krsort()与之相反。

数组统计/唯一函数

count()函数前面也提到过,作用是计算数组中数组元素的个数。

拆分、合并、分解数组函数

array_combine()和array_merge(),直接看代码
$one_array = array(“姓名”,”性别”,”年龄”,”职务”);
$two_array = array(“小曾”,”男”,23,”电子商务讲师”);

echo “

*********array_combine()后的新数组nc_array**********

”;
$nc_array = array_combine($one_array , $two_array);
print_r($nc_array);

结果为Array ( [姓名] => 小曾 [性别] => 男 [年龄] => 23 [职务] => 电子商务讲师 )

echo “

*********array_merge()后的新数组nm_array**********

”;
$nm_array = array_merge($one_array , $two_array);
print_r($nm_array);

结果为Array ( [0] => 姓名 [1] => 性别 [2] => 年龄 [3] => 职务 [4] => 小曾 [5] => 男 [6] => 23 [7] => 电子商务讲师 )
随机函数

这个大家应该会很常见,一些网站上的随机文章,随机广告,或者抽奖,PHP中都是用的这个原理。

主要函数有array_rand()和shuffle()。

array_rand()是从数组中随机取出一个或指定个数组元素,返回一个包含随机键名的数组。

shuffle()就是随机打乱一个数组。

到这里了。猪头博客最近忙,所以更新不稳定,呵呵,无所谓。在此申明,部分代码是参考我的讲师曾文兵老师的源代码。

以上就是PHP的数组应用基础(五)的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!