1、创建数组
用array()创建数组
形式如下:array array([item1[,item2...[,itemN]])
$languages = array("English", "Gaelic", "Spanish"); // 索引数组 $languages = array("Spain" => "Spanish", "Ireland" => "Gaelic", "United States" => "English"); //关联数组
2、用list()提取数组
// 打开users.txt文件 $users = fopen("users.txt", "r"); // 若未达到EOF,则获取下一行 while ($line = fgets($users, 4096)) { // 用explode()分离数据片段 list($name, $occupation, $color) = explode("|", $line); // 格式化数据并输出 printf("Name:%s <br/>", $name); printf("Occupation:%s<br/>", $occupation); printf("Favorite Color:%s<br/>", $color); } fclose($users);
Name:Nino Sanzi
Occupation:professional golfer
Favorite Color:green
3、用预定义的值范围填充数组 range()
$even = range(0, 20, 2); // $even = array(0, 2, 4, 6,....20); $letters = range("A", "F"); // $letters = array("A", "B", "C", "D", "E", "F");
4、测试数组 boolean is_array(mixed variable)
$states = array("Florida"); $state = "Ohio"; printf("$states is an array:%s <br/>", (is_array($states) ? "TRUE" :"FALSE")); printf("$state is an array:%s<br/>", (is_array($state)?"TRUE":"FALSE"));
5、输出数组
1 $states = array("Ohio", "Florida", "Texas"); 2 foreach($states as $state) { 3 echo "{$state}<br/>"; 4 }
Ohio Florida Texas
5.1、添加和删除数组元素
5.1.1 在数组头添加元素 array_unshift()函数在数组头添加元素
1 $states = array("Ohio", "New York"); 2 array_unshift($states, "California", "Texas"); 3 // $states = array("California", "Texas", "Ohio", "New York");
5.1.2 在数组尾添加元素 array_push()函数将值添加到数组的末尾
1 $states = array("Ohio", "New York"); 2 array_push($states, "California", "Texas"); 3 // $states = array("Ohio", "New York", "California", "Texas");
5.1.3 从数组头删除元素 array_shift()函数删除并返回数组中找到的第一个元素。其结果是如果使用的是数值键,则所有相应的值都会下移,而使用关联数组的数组不受影响。
1 $states = array("Ohio", "New York", "California", "Texas"); 2 $state = array_shift($states); 3 // $states = array("New York", "California", "Texas"); 4 // $state = "Ohio";
5.1.4 从数组尾删除元素 array_pop()函数删除并返回数组的最后一个元素
1 $states = array("Ohio", "New York", "California", "Texas"); 2 $state = array_pop($states); 3 // $states = array("Ohio", "New York", "California"); 4 // $state = "Texas";
5.2、定位数组元素
5.2.1、搜索数组: in_array()函数在数组中搜索一个特定值,如果找到这个值则返回TRUE,否则返回FALSE
1 $state = "Ohio"; 2 $states = array("California", "Hawaii", "Ohio", "New York"); 3 if (in_array($state, $states)) echo "Not to worry, $state is smoke-free!";
5.2.1.1、搜索关联数组键
如果在一个数组中找到一个指定的值,函数array_key_exists()返回TRUE,否则返回FALSE
1 $state["Delawate"] = "December 7, 1787"; 2 $state["Pennsylvania"] = "December 12, 1787"; 3 $state["Ohio"] = "March 1, 1803"; 4 if(array_key_exists("Ohio", $state)) 5 printf("Ohio joined the union on %s", $state["Ohio"]); 6 7 结果如下: 8 Ohio joined the union on March 1, 1803
5.2.1.2、搜索关联数组值
array_search()函数在一个数组中搜索一个指定的值,如果找到则返回相应的键,否则返回FALSE
1 1 $state["Ohio"] = "March 1"; 2 2 $state["Delaware"] = "December 7"; 3 3 $state["Pennsylvania"] = "December 12"; 4 4 $founded = array_search("December 7", $state); 5 5 if ($founded) 6 6 printf("%s was founded on %s",$founded, $state[$founded]); 7 7 输出如下: 8 8 Delawate was founded on December 7.
5.3、获取数组键
array_keys() 函数返回一个数组,其中包含所搜索数组中找到的所有键
1 $state["Delaware"] = "December 7,1787"; 2 $state["Pennsylvania"] = "December 12, 1787"; 3 $state["New Jersey"] = "December 18, 1787"; 4 $keys = array_keys($state); 5 print_r($keys); 6 7 Array([0]=>Delaware [1]=>Pennsylvania [2]=> New Jersey)
5.4、获取数组值
array_values() 函数返回一个数组中的所有值,并自动为返回的数组提供数值索引
1 $population = array("Ohio"=>"11,421,267", "Iowa"=>"2,936,760"); 2 print_r(array_values($population)); 3 4 Array([0]=>11,421,267 [1] => 2,936,760)
5.6、遍历数组
5.6.1 获取当前数组键
key()函数返回数组中当前指针所在位置的键
1 $capitals = array("Ohio"=>"Columbus", "Iowa"=>"Des Moines"); 2 echo "<p>Can you name the capitals of these states?</p>"; 3 while($key = key($capitals)) 4 { 5 printf("%s<br/>",$key); 6 next($capitals); 7 } 8 Can you name the capitals of these states? 9 Ohio 10 Iowa
5.6.2 获取当前数组值
current()函数返回数组中当前指针所在位置的数组值
1 $capitals = array("Ohio"=>"Columbus", "Iowa"=>"Des Moines"); 2 echo "<p>Can you name the states belonging to these capitals?</p>"; 3 4 while($capital = current($capitals)) 5 { 6 printf("%s <br/>", $capital); 7 next($capitals); 8 } 9 10 Can you name the states belonging to these capitals? 11 Columbus 12 Des Moines
5.6.3 获取当前数组键和值
each() 函数返回数组的当前键/值对,并将指针推进一个位置。其形式如下:
array each(array array)
返回的数组包含4个键,键0和key包含键名,而键1和value包含相应的数据。如果执行each()前指针位于数组末尾,则返回FALSE
5.6.4 移动数组指针
1、将指针移动到下一个数组位置
next()函数返回紧接着放在当前数组指针下一个位置的数组值
1 $fruits = array("apple", "orange", "banana"); 2 $fruit = next($fruits); //返回"orange" 3 $fruit = next($fruits); // 返回"banana"
2、将指针移动到前一个数组位置
prev()函数返回位于当前指针前一个位置的数组值,如果指针本来就位于数组的第一个位置,则返回FALSE
3、将指针移到第一个数组位置
reset()函数用于将数组指针设置会数组的开始位置
4、将指针移动到最后一个数组位置
end()函数将指针移动到数组的最后一个位置,并返回最后一个元素
1 $fruits = array("apple", "orange", "banana"); 2 $fruit = current($fruits); //返回apple 3 $fruit = end($fruits); //返回banana
5.6.5 向函数传递数组值
array_walk()函数将数组中的各个元素传递到用户自定义元素。
1 <?php 2 function sanitize_data(&$value,$key) 3 { 4 $value = strip_tags($value); 5 } 6 array_walk($_POST['keyword'], "sanitize_data"); 7 ?>
<form action="submitdata.php" method="post"> <p> Provide up to six keywords that you believe best describe the state in which you live: </p> <p>Keyword 1:<br/> <input type="text" name="keyword[]" size="20" maxlength="20" value="" /></p> <p>Keyword 2:<br/> <input type="text" name="keyword[]" size="20" maxlength="20" value="" /></p> <p>Keyword 3:<br/> <input type="text" name="keyword[]" size="20" maxlength="20" value="" /></p> <p>Keyword 4:<br/> <input type="text" name="keyword[]" size="20" maxlength="20" value="" /></p> <p>Keyword 5:<br/> <input type="text" name="keyword[]" size="20" maxlength="20" value="" /></p> <p>Keyword 6:<br/> <input type="text" name="keyword[]" size="20" maxlength="20" value="" /></p> <p><input type="submit" value="Submit!"></p> </form>
5.6.7 确定数组的大小和唯一性
5.7.1 确定数组的大小
count()函数返回数组中值的总数
$garden = array("a", "b", "c", "d"); echo count($garden) // 4
5.7.2 统计数组元素出现的频度
array_count_values()函数返回一个包含关联数组键/值对的数组
1 $states = array("Ohio", "Iowa", "Arizona", "Iowa", "Ohio"); 2 $stateFrequency = array_count_values($states); 3 print_r($stateFrequency); 4 5 Array([Ohio]=>2 [Iowa]=> 2 [Arizona]=>1)
5.7.3 确定唯一的数组元素
array_unique()函数会删除数组中所有重复的值,返回一个由唯一值的数组
1 $a = array("a", "b", "c", "b", "a"); 2 $b = array_unique($a); 3 print_r($b); 4 5 Array([0]=>a [1]=>b [2]=>c)
5.8 数组排序
5.8.1、逆置数组元素排序
array_reverse()函数将数组中元素的顺序逆置
1 $states = arrray("Delaware", "Pennsylvania", "New Jersey"); 2 print_r(array_reverse($states)); 3 4 Array([0]=>New Jersey [1]=>Pennsylvania [2]=> Delaware)
5.8.2、置换数组键和值
array_flip()函数将置换数组中及其相应值的角色
$state = array("Delaware", "Pennsylvania", "New Jersey"); $state = array_flip($state); print_r($state); Array([Delaware]=>0 [Pennsylvania]=>1 [New Jersey]=>2)
5.8.3、数组排序
sort()函数对数组进行排序
void sort(array array, [, int sort_flags])
sort_flags参数可选
SORT_NUMERIC 按数值排序
SORT_REGULAR 按ASCII值对元素排序
SORT _STRING 按接近人所认知的正确顺序对元素排序
$grades = array(42, 98, 100, 100, 43, 12); sort($grades); print_r($grades); Array([0]=>12 [1]=>42 [2]=>43 [3]=>98 [4]=>100 [5]=>100) 值得注意的一点是键/值关联不再保持 $states = array("OH"=>"Ohio", "CA"=>"California", "MD"=>"Maryland"); sort($states); print_r($states); Array([0]=>California [1]=>Maryland [2]=>Ohio)
1.保持键值对的条件下对数组排序
asort()函数与sort()相同,以升序对数组排序,只不过它保持键值的关联
2. 以逆序对数组排序
rsort()函数与sort()相同,只不过它以相反的顺序(降序)对数组元素排序。
3.保持键值对的条件下以逆序对数组排序
arsort()会保持键值的关联,以逆序对数组排序
4.数组自然排序
natsort()函数提供了一种相当于人们平常使用的排序机制
5.不区分大小写的自然排序
natcasesort()
6.按键值对数组排序
ksort()函数按键对数组排序,如果成功返回TRUE,失败将返回FALSE
7. 以逆序对数组键排序
krsort()函数的操作与ksort()相同,也按键排序,只不过它将以逆序排序
8.根据用户自定义规则排序
usort()函数
<?php $dates = array('10-10-2011', '2-17-2010', '2-16-2010', '1-01-2013', '10-10-2012'); sort($dates); echo "<p>Sorting the array using the sort() function.</p>"; print_r($dates); natsort($dates); echo "<p>Sorting the array using the natsort() funciton:</p>"; print_r($dates); function DateSort($a, $b) { // 如果日期相等,则什么也不做 if ($a == $b) return 0; // 反汇编日期 list($amonth, $aday, $ayear) = explode('-', $a); list($bmonth, $bday, $byear) = explode('-', $b); //如果没有前导0,则为月份加前导0 $amonth = str_pad($amonth, 2, "0", STR_PAD_LEFT); $bmonth = str_pad($bmonth, 2, "0", STR_PAD_LEFT); // 如果没有前导0,则为日份加前导0 $aday = str_pad($aday, 2, "0", STR_PAD_LEFT); $bday = str_pad($bday, 2, "0", STR_PAD_LEFT); // 重组日期 $a = $ayear . $amonth . $aday; $b = $byear . $bmonth . $bday; // 确定是否$a > $date b return ($a > $b) ? 1 : -1; } usort($dates, 'DateSort'); echo "<p>Sorting the array using the user-defined DateSort() function:</p>"; print_r($dates); ?> <p>Sorting the array using the sort() function.</p>Array ( [0] => 1-01-2013 [1] => 10-10-2011 [2] => 10-10-2012 [3] => 2-16-2010 [4] => 2-17-2010 ) <p>Sorting the array using the natsort() funciton:</p>Array ( [0] => 1-01-2013 [3] => 2-16-2010 [4] => 2-17-2010 [1] => 10-10-2011 [2] => 10-10-2012 ) <p>Sorting the array using the user-defined DateSort() function:</p>Array ( [0] => 2-16-2010 [1] => 2-17-2010 [2] => 10-10-2011 [3] => 10-10-2012 [4] => 1-01-2013 )
5.9 合并、拆分、接合和分解数组
5.9.1 合并数组
array_merge()函数将数组合并在一起,返回一个联合的数组。所得到的数组以第一个输入数组参数开始,按后面数组参数出现的顺序依次追加
$face = array("J", "Q", "K", "A"); $numbered = array("2", "3", "4", "5", "6", "7", "8", "9"); $cards = array_merge($face, $numbered); shuffle($cards); // 洗牌 print_r($cards); Array([0]=>8 [1]=>6 [2]=>K [3]=>Q [4]=>9 [5]=>5 [6]=>3 [7]=> 2 [8]=> 7 [9]=>4 [10]=>A [11]=>J)
5.9.2 递归追加数组
array_merge_recursive()函数与array_merge()相同,可以将两个或多个数组合并在一起,形成一个联合的数组。两者之间的区别在于,当某个输入数组中的某个键已经存在与结果数组中时该函数会采取不同的处理方式。array_merge()会覆盖前面存在的键值对,将其替换为当前输入数组中的键值对,而array_merge_recursive()将两个值合并在一起,形成一个新的数组并以原有的键作为数组名。
$class1 = array("John"=>100, "James"=>85); $class2 = array("Micky"=>78, "John"=>45); $classScores = array_merge_recursive($class1, $class2); print_r($classScores); Array([John]=>Array([0]=>100 [1]=>45) [James]=>85 [Micky]=>78)
5.9.3 合并两个数组
array_combine()函数会生成一个新数组,这个数组有一组提交的键和对应的值组成
$abbreviations = array("AL", "AK", "AZ", "AR"); $states = array("Alabama", "Alaska", "Arizona", "Arkansas"); $stateMap = array_combine($abbreviations, $states); print_r($stateMap); Array([AL]=>Alabama [AK]=>Alaska [AZ]=>Arizona [AR]=>Arkansas)
5.9.4 拆分数组
array_slice()函数将返回数组中的一部分,从键offset开始,到offset+length位置结束
$states = array("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut"); $subset = array_slice($states, 4); print_r($subset); Array([0]=>California [1]=>Colorado [2]=>Connecticut) $states = array("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut"); $subset = array_slice($states, 2, -2); print_r($subset); Array([0]=>Arizona [1]=>Arkansas [2]=>California)
5.9.5 接合数组
array_splice()函数会删除数组中从offset开始到offset+length结束的所有元素,并以数组的形式返回所删除的元素
$states = array("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Connecticut"); $subject = array_splice($states, 4); print_r($states); print_r($subject); Array([0]=>Alabama [1]=>Alaska [2]=>Arkansas [3]=>California ) Array([0]=>California [1]=>Connecticut) 注意:不包含offset+length上的元素
5.9.6 求数组的交集
array_intersect()函数返回一个保留了键的数组,这个数组只由第一个数组中出现的且在其他每个输入数组中都出现的值组成
$array1 = array("OH", "CA", "NY", "HI", "CT"); $array2 = array("OH", "CA", "HI", "NY", "IA"); $array3 = array("TX", "MD", "NE", "OH", "HI"); $intersection = array_intersect($array1, $array2, $array3); print_r($intersection) Array([0]=>OH [1]=>HI)
5.9.7 求关联数组的交集
array_intersect_assoc()与array_intersect()基本相同,只不过它在比较中还考虑了数组的键
$array1 = array("OH"=>"Ohio", "CA"=>"California", "Hi"=>"Hawaii"); $array2 = array("50"=>"Hawaii", "CA"=>"California", "OH"=>"Ohio"); $array3 = array("TX"=>"Texas", "MD"=>"Maryland", "OH"=>"Ohio"); $intersection = array_intersect_assoc($array1,$array2, $array3); print_r($intersection); Array([OH]=>Ohio);
5.9.8 求数组的差集
函数array_diff()返回出现在第一个数组中但其他输入数组中没有的值
$array1 = array("OH", "CA", "NY", "HI", "CT"); $array2 = array("OH", "CA", "HI', "NY", "IA'); $array3 = array("TX", "MD", "NE", "OH", "HI"); $diff = array_diff($array1, $array2, $array3); print_r($diff); Array([0]=>CT)
5.9.9 求关联数组的差集
array_diff_assoc()与array_diff()基本相同,只是它在比较时还考虑了数组的键
5.10.1 返回一组随机的键
array_rand()函数将返回数组中的一个或多个键
$states = array("Ohio"=>"Columbus", "Iowa"=>"Des Moines", "Arizona"=>"Phoenix"); $randomStates = array_rand($states, 2); Array([0]=>Arizona [1]=>"Ohio");
5.10.2 随机洗牌数组元素
shuffle()函数随机地对数组元素重新排序
$arr = array("a", "b", "c"); shuffle($arr); print_r($arr); Array([0]=>b [1]=>c [2]=>a)
1. 对数组中的值求和
array_sum()将input_array中所有值加在一起,返回最终的和
<?php $arr = array(42, "Hello", 43); $total = array_sum($arr); print $total; ?> 85
2.划分数组
array_chunk()函数将input_array分解为一个多维数组,这个多维数组由多个包含size个元素的数组所组成。
$cards = array("jh", "js', "jd', "jk"); // 洗牌 shuffle($cards); // 用array_chunk()均匀划分为4份 $hands = array_chunk($cards, 2); print_r($hands); Array([0]=>Array([0]=>jh [1]=>jk)) Array([1]=>Array([0]=>js [1]=>jd))