Home  >  Article  >  php教程  >  PHP10个关联数组的技巧

PHP10个关联数组的技巧

WBOY
WBOYOriginal
2016-06-06 19:56:08993browse

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 7、随机数组排序 在FlashCard程序中还涉及到另一种随机排序技术,这时你要使用shuffle()函数实现数组项目的随机排序。 $capitals = array( 'Arizona' = 'Phoenix', 'Alaska' = 'Juneau', 'Alabama

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入

 

  7、随机数组排序

  在FlashCard程序中还涉及到另一种随机排序技术,这时你要使用shuffle()函数实现数组项目的随机排序。

  $capitals = array(

  'Arizona' => 'Phoenix',

  'Alaska'  => 'Juneau',

  'Alabama' => 'Montgomery'

  );

  shuffle($capitals);

  如果不需要打乱数组顺序,你只是想随机选择一个值,那么使用array_rand()函数即可。

  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
", $state, $capital);

  }

  // The capital of Arizona is Phoenix

  // The capital of Alaska is Juneau

  // The capital of Alabama is Montgomery

  这仅仅是SPL众多伟大功能中的一个,一定要阅读PHP手册了解更多信息。

  [1] [2] 

PHP10个关联数组的技巧

Statement:
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