array_filter(),返回新的数组<?php
header('content-type:text/html; charset=utf-8');
//定义数组
$array = [
['ISBN'=>'9787302466529', 'title'=>'ThinkPHP实战', 'pub'=>'清华大学出版社', 'price'=>49],
['ISBN'=>'9787121122910', 'title'=>'ThinkPHP从入门到精通', 'pub'=>'电子工业出版社', 'price'=>59],
['ISBN'=>'9787111569756', 'title'=>'ThinkPHP实例教程', 'pub'=>'机械工业出版社', 'price'=>58]
];
echo '
';
echo '原数组:
';
print_r($array);//原样输出键、值(key、value)
//使用回调函数处理
echo '使用array_filter()的回调函数处理:
';
echo '1:按完整书名过滤
';
$result = array_filter($array, function (&$value) {//加&传递参数引用,可以修改,不加&仅传递参数值,修改无效
if ($value['title'] == 'ThinkPHP实战') {
return true; //返回true,放回到结果中
}
return false; //返回false,这个值就不会出现在结果中
});
print_r($result);
echo '2:按书名中的某个字过滤
';
$result = array_filter($array, function ($value) {//加&传递参数引用,可以修改,不加&仅传递参数值,修改无效
if ( strstr($value['title'] , '实') ) { //
return $value; //直接返回原参数,作用与return true是一样的
}
return false; //返回false,这个值就不会出现在结果中
});
print_r($result);
echo '3:按书价过滤
';
$result = array_filter($array, function ($value) {
if ( $value['price']>50 ) {
return $value;
}
return false;
});
print_r($result);
array_walk(),返回boolean 值,具体处理结果要在回调函数中赋值给其它数组<?php
header('content-type:text/html; charset=utf-8');
//创建数组
$array = [50,60,63,65,70,75,79,80,85,86,89,90,96];
echo '
';
echo '原数组:
';
print_r($array);//原样输出键、值(key、value)
//使用回调函数处理
echo '使用array_walk()的回调函数处理:
';
//输出处理后的数组
$grade_standard = ['及格'=>60, '中'=>70, '良'=>80, '优'=>90];
$grade_count = ['不及格'=>0, '及格'=>0, '中'=>0, '良'=>0, '优'=>0];
array_walk($array, function ($value,$key,$grade_standard){
if($value >= $grade_standard['优'] ){
$GLOBALS['grade_count']['优']++;
} elseif($value >= $grade_standard['良'] ){
$GLOBALS['grade_count']['良']++;
} elseif($value >= $grade_standard['中'] ){
$GLOBALS['grade_count']['中']++;
} elseif($value >= $grade_standard['及格'] ){
$GLOBALS['grade_count']['及格']++;
} else {
$GLOBALS['grade_count']['不及格']++;
};
},$grade_standard);
echo '
';
echo '成绩统计:
';
print_r($grade_count);
array_map(),单个数组相当于遍历,两个或多个数组相当于组合为一个新的多维数组,原数组的每个值,都是新数组的一级数组的元素数组(二级数组)的值。<?php
header('content-type:text/html; charset=utf-8');
//创建数组
$grade_standard_score = [60, 70, 80, 90];
$grade_standard_grade = ['及格', '中', '良', '优'];
//使用回调函数处理
echo '使用array_map()的回调函数处理:
';
//合并数组
$grade_standard = array_map(null,$grade_standard_grade,$grade_standard_score);
//输出合并后的数组
echo '
';
echo '成绩等级:
';
foreach(array_reverse($grade_standard) as $item)//从高到低输出
{
list($key,$value) = $item;
echo '高于'.$value.':'.$key.'
';
}