使用数组

来源:互联网 发布:linux开机运行脚本 编辑:程序博客网 时间:2024/05/17 05:16

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>数组</title>
</head>

<body>
<?php
//数字索引数组的初始化
$products = array('Tires','oil','Spark Plugs');
//访问数组
echo $products[0].'<br>'.$products[1].'<br>'.$products[2].'<br>';

//创建1 - 10 的数字数组
$numbers = range(1,10);

//使用for循环遍历数组
for($i = 0; $i < count($numbers); $i++)
{
 echo $numbers[$i].'<br>';
}

//索引数组
$prices = array('Tires'=>100,'Oil'=>10);
//使用foreach循环访问索引数组
foreach($prices as $key=>$value)
{
 echo $key.'=>'.$value.'<br>';
}

//合并数组
$productss = $products + $numbers;

//多维数组
$pros = array(array('TIR',100),
    array('OLL',10));
//使用for循环遍历多维数组,count()函数用来计算数组的元素个数
for($i = 0; $i < count($pros); $i++) //count($pros)返回二维数组的行数
{
 for($j = 0; $j < count($pros[$i]); $j++) //count($pros[$i])返回二维数组的列数
 {
  echo $pros[$i][$j].'<br>';
 }
}

//创建索引字多维数组
$pross = array(array('code'=>'TIR',
      'price'=>'100'),
      array('code'=>'OLL',
      'price'=>10));
//访问索引字多维数组
for($i = 0; $i < count($pross); $i++)
{
 echo $pross[$i]['code'].'=>'.$pross[$i]['price'].'<br>';
}

//下标数组排序
sort($productss,SORT_STRING);
for($i = 0; $i < count($productss); $i++)
{
 echo $productss[$i].'<br>';

//索引数组排序
asort($prices); //按元素值排序
//使用foreach循环访问索引数组
foreach($prices as $key=>$value)
{
 echo $key.'=>'.$value.'<br>';
}

ksort($prices); //按索引排序
//使用foreach循环访问索引数组
foreach($prices as $key=>$value)
{
 echo $key.'=>'.$value.'<br>';
}

//反向排序函数 rsort();  arsort(); krsort();


//多维数组的排序
function compare($x,$y) //定义排序的比较函数
{
 if($x[1] == $y[1])  //按多维数组的第二列排序
 {
  return 0;
 }
 elseif($x[1] < $y[1])
 {
  return -1; //如果小于,返回-1表示按升序排列,返回1表示按降序排列
 }
 else
 {
  return 1;
 }
}

usort($pross,'compare');  //usort()是多维数组的排序函数,第二个参数是执行比较的函数名称
//访问索引字多维数组
for($i = 0; $i < count($pross); $i++)
{
 echo $pross[$i]['code'].'=>'.$pross[$i]['price'].'<br>';
}

//数组随机排序函数
shuffle($numbers);
for($i = 0; $i < count($numbers); $i++)
{
 echo $numbers[$i].'<br>';
}

/*array_reverse()函数
这个函数使用数组作为参数,返回一个与原来数组相同但顺序相反的数组,这只是产生一个副本,原来的数组没变
*/
$numbers = array_reverse($numbers);
for($i = 0; $i < count($numbers); $i++)
{
 echo $numbers[$i].'<br>';
}

/*统计数组元素个数的两个函数,这两个函数用数组名作为参数
count(); sizeof();*/


?>
</body>
</html>

原创粉丝点击