1.数组的键/值操作函数
array_values($arr);
array_keys($arr);
array_flip($arr);
in_array("apple",$arr);
array_search("apple",$arr);
array_key_exists("apple",$arr);
isset($arr[apple]):
2.统计数组元素的个数和唯一性
count();
array_count_values();
array_unique();
3.使用回调函数处理数组的函数
------------------------------------------------------------------------------------
array_walk($arr,'function','words');
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function test_alter(&$item1, $key, $prefix)
{
$item1 = "$prefix: $item1";
}
function test_print($item2, $key)
{
echo "$key. $item2
\n";
}
echo "Before ...:\n";
array_walk($fruits, 'test_print');
array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";
array_walk($fruits, 'test_print');
Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple
------------------------------------------------------------------------------------
array_map("function",$arr1,$arr2);
function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
Array
(
[0] => 1
[1] => 8
[2] => 27
[3] => 64
[4] => 125
)
------------------------------------------------------------------------------------
array_filter($arr,"function");
function odd($var)
{
return($var & 1);
}
function even($var)
{
return(!($var & 1));
}
$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);
echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
Odd :
Array
(
[a] => 1
[c] => 3
[e] => 5
)
Even:
Array
(
[0] => 6
[2] => 8
[4] => 10
[6] => 12
)
------------------------------------------------------------------------------------
array_reduce($arr,"function","*");
function sum($carry, $item)
{
$carry += $item;
return $carry;
}
function product($carry, $item)
{
$carry *= $item;
return $carry;
}
$a = array(1, 2, 3, 4, 5);
$x = array();
var_dump(array_reduce($a, "sum"));
var_dump(array_reduce($a, "product", 10));
var_dump(array_reduce($x, "sum", "No data to reduce"));
------------------------------------------------------------------------------------
4.数组的排序函数
sort($arr);
rsort($arr);
usort($arr,"function");
asort($arr);
arsort($arr);
uasort($arr,"function");
ksort($arr);
krsort($arr);
uksort($arr,"function");
natsort($arr);
natcasesort($arr);
5.拆分、合并、分解和接合数组
array_slice()
array_splice()
array_combine()
array_merge();
array_intersect();
array_intersect_assoc($arr1,$arr2);
array_diff();
array_diff_assoc($arr1,$arr2,$arr3);
6.数组与数据结构
array_push();
array_pop();
array_unshift();
array_shift();
unset();
其他有用的数组处理函数
range(0,12);
array_reverse($arr,TRUE);
array_rand($arr,2);
shuffle($arr);
array_sum($arr);