PHP中的数组

来源:互联网 发布:姓名签名设计软件 编辑:程序博客网 时间:2024/05/22 14:29

数组用途

  • array
  • list/vector
  • hash table
  • dictionary
  • collection
  • queue
  • stack
  • tree
  • multidimensional array

PHP数组本质

  • hash table

数组定义

  • 注意
    • The comma after the last array element is optional and can be omitted.格式约束
    • As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].格式约束
    • The key can either be an integer or a string. The value can be of any type. key如果采用别的类型的话会发生类型转换或报warning,避免这种情况出现
    • If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.数据覆盖
    • PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays.key 类型是可以混合使用的
    • The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.key的值是默认以最大一个有效int类型的key标准增加的

-

# array    $array = ("Monday",    "Tursday",    "Wednesday",    "Thursday",    "Friday",    "Saturday",    "Sunday",);# dictionary    $person = array(        "id" => 12345,        "name" => "chenxilin",        "age" => 25,);

数组引用

  • [key] 或 {key} 多维数组可多个
  • As of PHP 5.4 it is possible to array dereference the result of a function or method call directly.
  • As of PHP 5.5 it is possible to array dereference an array literal.
  • 注意:
    • 特殊赋值:arr[] = value,用于追加value值到数组中,key采用数组中最大一个有效int类型的key增加;
    • 如果该数组arr不存在或原来不是数组时,这会被创建一个新的数组出来并添加元素。

数组修改、删除

  • To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it.使用unset方法,可以删除整个数组或其中某个key/value

数组遍历

foreach ($arr as $key => $value ) {    // do something for $key and $value;}

有用的方法

  • array_value($arr) 返回一个re-index的数组,使得key中int类型是从0开始连续增长的而不会断开。
  • count($arr) 获得数组长度
  • sort($arr) … 数组排序算法

迭代器接口实现foreach

实现构造方法和以下接口
1. Iterator::current — Return the current element
2. Iterator::key — Return the key of the current element
3. Iterator::next — Move forward to next element
4. Iterator::rewind — Rewind the Iterator to the first element
5. Iterator::valid — Checks if current position is valid

0 0
原创粉丝点击