1. 数组的遍历
$price = [
'Oil' => 100,
'Tire' => 10,
'Spark Plugs' => 4,
];
foreach ($newPrice as $item => $price) {
echo $item . ' price is : ' . $price . "\n";
}
2. 数组排序
sort 与 rsort
$products = [
'Tires',
'Oil',
'Spark Plugs',
];
// 排序
sort($products, SORT_STRING);
// 反向排序
rsort($products, SORT_STRING);
按数组的值排序 asort与arsort
asort($products, SORT_NUMERIC);
arsort($products, SORT_NUMERIC);
按数组的键排序 ksort与krsort
ksort($products, SORT_STRING);
krsort($products, SORT_STRING);
用户自定义排序 usort(自我理解 user sort)
// user sort
$products = [
['TIR', 'Tires', 100],
['OIL', 'Oil', 10],
['SPK', 'Spark Plugs', 4],
];
function compare ($x, $y) {
return $x[2] - $y[2];
}
usort($products, 'compare');
随机排序 shuffle
shuffle($products);
反向排序
array_reverse($products);
数组其他操作 current(), pos(), next(), prev(), reset(), end()
/**
* 在数组中浏览
* each(); // PHP7.2中已废弃
*
* current(); 当前元素
* pos();
*
* prev();
* next();
*
* reset();
* end();
*
*/
对数组的每个元素应用任何函数 array_walk()
function toUpperCase ($a) {
echo strtoupper($a);
}
array_walk($letters, 'toUpperCase');
统计数组元素个数
count($letters);
sizeof($letters);
// 统计每个特定的值在数组中出现的次数
array_count_values($letters);
将数组转成标题变量 extract()
// 将数组转成标量
$person = [
'name' => 'baiqb',
'age' => 28,
'sex' => 'male',
];
extract($person, EXTR_PREFIX_ALL, 'person');
echo "\n";
echo $person_name . "\n";
echo $person_age . "\n";
echo $person_sex . "\n";
网友评论