Detailed explanation of simple cases of PHP array operations

墨辰丷
Release: 2023-03-28 19:00:01
Original
1560 people have browsed it

这篇文章主要介绍了PHP数组操作,结合简单实例形式分析了php数组转换、排序、移除等相关操作技巧,需要的朋友可以参考下

这个是一道简单的PHP数组入门题


$Str = "as5454654%^$%^$7675dhasjkdhh12u123123asdasd";
//将上面的统计上面字符串不同字符和出现的次数。
Copy after login


实现方式:将字符串转换成数组,在通过对数组的操作得到相应的结果。


$len = strlen($str);
//数组存在数组中
$array = array();
for($i=0;$i<$len;$i++)
{
  array_push($array,substr($str,$i,1));
}
Copy after login


根据上面的转换函数,我们得到的了,我们想要的结果。

接下来用三种方式来完成上面的。


//方法1
//对数组进行sort()排序
$arr = sort($array);
//去掉重复值
$arr1 = array_unique($array);
//打印数组$arr1你将发现,你继续来需要做的事了。注意键值直接的关系
Copy after login


效果图

下面来看看方法二:


//无比风骚的方法二
$arr2 = array_count_values($array);
//打印数组$arr2 所有问题都解决了
Copy after login


效果图

是不觉得方法二很坑爹呀~

注意:凡是可以用到PHP自动函数的,最好是用,理由我不说,你也应该懂

方法三:

我这里只说思想:运用ACM思想,对元素数组进行快排后,再对数组进行分块处理。

效果图

看看这个函数给你上面提示:


array array_splice ( array $input , int $offset [, int $length< [, array $replacement ]] )
//把 input 数组中由 offset 和 length 指定的单元去掉,如果提供了 replacement 参数,
//则用 replacement 数组中的单元取代。返回一个包含有被移除单元的数组。注意 input 中的数字键名不被保留。
Copy after login


解决问题的方式很多,我现在就想到这三种,一个简单的问题,多想想。代码就会越敲越少。这就是进步。


总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

phpcms搜索功能实现

PHP处理苹果APP内购后到服务端的二次验证(项目经验)

PHP项目集成微信端扫码支付API(境内支付)


The above is the detailed content of Detailed explanation of simple cases of PHP array operations. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!