第一章 高级PHP技巧
1.1 多维数组排序
1.1.1 多维数组排序
$a=array(
array('key1'=>940,'key2'=>'blah'),
array('key1'=>23,'key2'=>'this'),
array('key1'=>894,'key2'=>'that')
);
print_r($a);
function asc_number_sort($x,$y){
if($x['key1']>$y['key1']){
return true;
}elseif($x['key1']
return false;
}else{
return 0;
}
}
usort($a,'asc_number_sort');
$a=array(
array('key1'=>940,'key2'=>'blah'),
array('key1'=>23,'key2'=>'this'),
array('key1'=>894,'key2'=>'that')
);
function string_sort($x,$y){
return strcasecmp($x['key2'],$y['key2']);
}
usort($a,'string_sort');
$students=array(
256=>array('name'=>'John','grade'=>98.5),
2=> array('name'=>'Vance','grade'=>85.1),
9=> array('name'=>'Stephen','grade'=>94.0),
364=>array('name'=>'Steve','grade'=>85.1),
68=> array('name'=>'Rob','grade'=>74.6)
);
function name_sort($x,$y){
return strcasecmp($x['name'],$y['name']);
}
function grade_sort($x,$y){
return ($x['grade']
}
echo '
Array As Is
'.print_r($students,1).'';
uasort($students,'name_sort');
echo '
Array Sorted By Name
'.print_r($students,1).'';
uasort($students,'grade_sort');
echo '
Array Sorted By Grade
'.print_r($students,1).'';
1.1.2 数据库驱动的数组
$dbc=mysqli_connect('localhost','root','','php');
if(($_SERVER['REQUEST_METHOD']=='POST')&& !empty($_POST['task'])){
if(isset($_POST['parent_id'])&& filter_var($_POST['parent_id'],FILTER_VALIDATE_INT,array('min_rang'=>1))){
$parent_id=$_POST['parent_id'];
}else{
$parent_id=0;
}
$task=mysqli_real_escape_string($dbc,strip_tags($_POST['task']));
$q="insert into tasks(parent_id,task) values($parent_id,'$task')";
$r=mysqli_query($dbc,$q);
if(mysqli_affected_rows($dbc)==1){
echo '
The task has been added
';
}else{
echo '
The task chould not be added!
';
}
}
echo '
Add a Task
Task:
Parent Task:None';
$q='select task_id,parent_id ,task from tasks where date_completed="0000-00-00 00:00:00" order by date_added ASC';
$r=mysqli_query($dbc,$q);
$task=array();
while(list($task_id,$parent_id,$task)=mysqli_fetch_array($r,MYSQL_NUM)){
echo "$task\n";
$tasks[]=array('task_id'=>$task_id,'parent_id'=>$parent_id,'task'=>$task);
}
echo '
';
function parent_sort($x,$y){
return ($x['parent_id']>$y['parent_id']);
}
usort($tasks,'parent_sort');
echo '
Current To-Do List
foreach($tasks as $task){
echo "
{$task['task']}\n";
}
echo '
';
1.2 高级函数定义
递归函数
静态变量
以引用方式接收值
匿名函数
1.2.1 递归函数
递归 recursion 就是函数自己调用自己的行为。
global $tasks;
echo '
- ';
foreach($parent as $task_id=>$todo){
echo "
".$todo;
if(isset($tasks[$task_id])){
make_list($tasks[$task_id]);
}
echo "
";
}
echo "
";
}
$dbc=mysqli_connect('localhost','root','','php');
$q='select task_id,parent_id,task from tasks where date_completed="0000-00-00 00:00:00" order by parent_id,date_added asc';
$r=mysqli_query($dbc,$q);
$tasks=array();
while(list($task_id,$parent_id,$task)=mysqli_fetch_array($r,MYSQLI_NUM)){
$tasks[$parent_id][$task_id]=$task;
}
echo '
'.print_r($tasks,1).'';
make_list($tasks[0]);