<?php
/**
* Created by PhpStorm.
* User: wei19
* Date: 2019/1/19
* Time: 14:14
*/
/*
* 多维数组创建及遍历
*/
$books = array(
array('PHP','computer',42),
array('VC++','computer',36),
array('Arr','医学书籍',100),
array('Science','英语',56)
);
echo "书籍名称:".$books[0][0]."书籍类型:".$books[0][1]."价格:".$books[0][2]."<br />";
echo "书籍名称:".$books[1][0]."书籍类型:".$books[1][1]."价格:".$books[1][2]."<br />";
echo "书籍名称:".$books[2][0]."书籍类型:".$books[2][1]."价格:".$books[2][2]."<br />";
echo "书籍名称:".$books[3][0]."书籍类型:".$books[3][1]."价格:".$books[3][2]."<br />";
echo "使用for循环来输出数组内容:"."<br />";
for ($i=0; $i<4;$i++){
for ($j=0; $j<3; $j++){
echo "@".$books[$i][$j];
}
echo "<br />";
}
//包含有描述性质的索引创建方式
$book2 = array(
array('bookName'=>'VC++','bookType'=>'computer','bookPrice'=>42),
array('bookName'=>'PHP','bookType'=>'array','bookPrice'=>24),
array('bookName'=>'VC','bookType'=>'science','bookPrice'=>48),
array('bookName'=>'VC+','bookType'=>'book','bookPrice'=>98)
);
/*
* 多维数组排序:usort()
*/
//对$books按照书籍类型升序排序
function ascending($x,$y){
if ($x[0]==$y[0]){
return 0;
}else if ($x[0]<$y[0]){
return -1;
}else{
return 1;
}
}
//降序
function descending($x,$y){
if ($x[2]==$y[2]){
return 0;
}else if ($x[2]<$y[2]){
return 1;
}else{
return -1;
}
}
usort($books,'ascending');
echo "按照书籍类型排序后:"."<br />";
for ($i=0;$i<4;$i++){
for ($j=0;$j<3;$j++){
echo "@".$books[$i][$j];
}
echo "<br />";
}
//对于相关数组,使用uasort(),uksort()排序
function descending_book2($x,$y){
if ($x['bookPrice']==$y['bookPrice']){
return 0;
}else if ($x['bookPrice']<$y['bookPrice']){
return 1;
}else{
return -1;
}
}
usort($book2,'descending_book2');//按照值排序
foreach ($book2 as $key=>$value){
foreach($value as $key2 => $value2){
echo $key2.'=>'.$value2."~~~~~~~~"; //二维关联数组的遍历
}
echo "<br />";
}
/*
* 知识点:数组函数
*/
PHP学习笔记与Demo(二)
最新推荐文章于 2023-11-27 09:19:31 发布