8、确定键和值是否存在
你可以使用in_array()函数确定一个数组元素是否存在。
- $capitals = array(
- 'Arizona' => 'Phoenix',
- 'Alaska' => 'Juneau',
- 'Alabama' => 'Montgomery'
- );
- if (in_array("Juneau", $capitals))
- {
- echo "Exists!";
- } else {
- echo "Does not exist!";
- }
很少有人知道这个函数也可以确定一个数组键是否存在,在这一点上,它和array_key_exists()函数的功能一样。
- $capitals = array(
- 'Arizona' => 'Phoenix',
- 'Alaska' => 'Juneau',
- 'Alabama' => 'Montgomery'
- );
- if (array_key_exists("Alaska", $capitals))
- {
- echo "Key exists!";
- } else {
- echo "Key does not exist!";
- }
9、搜索数组
你可能想搜索数组资源,这样用户就可以方便地用一个特定的州府检索关联的州,可以通过array_search()函数实现数组搜索。
- $capitals = array(
- 'Arizona' => 'Phoenix',
- 'Alaska' => 'Juneau',
- 'Alabama' => 'Montgomery'
- );
- $state = array_search('Juneau', $capitals);
- // $state = 'Alaska'
10、标准PHP库
标准PHP库(Standard PHP Library,SPL)为开发人员提供了许多数据结构,迭代器,接口,异常和其它以前PHP语言没有的功能,使用这些功能可以通过面向对象的语法遍历数组。
- $capitals = array(
- 'Arizona' => 'Phoenix',
- 'Alaska' => 'Juneau',
- 'Alabama' => 'Montgomery'
- );
- $arrayObject = new ArrayObject($capitals);
- foreach ($arrayObject as $state => $capital)
- {
- printf("The capital of %s is %s<br />", $state, $capital);
- }
- // The capital of Arizona is Phoenix
- // The capital of Alaska is Juneau
- // The capital of Alabama is Montgomery
这仅仅是SPL众多伟大功能中的一个,一定要阅读PHP文档了解更多信息。
原文明:10 PHP Tricks for Associative Array Manipulation 黄永兵 译
原文链接:http://www.phpbuilder.com/columns/associative-array-manipulation/Jason_Gilmore12092010.php3
转载于:https://blog.51cto.com/riddle/525588