标签:
一数组的建立以及输出
<?php
$products = array (‘Tires‘,‘Oil‘,‘Spark Plugs‘);
for($i = 0;$i < 3; $i ++)
echo "$products[$i] ";
echo ‘<br/>‘;
foreach($products as $current)
echo $current.‘ ‘;
echo ‘<br/>‘;
$prices=array(‘Tires‘=>100,‘Oil‘=>10,‘Spark Plugs‘=>4);
foreach($prices as $key => $value)
echo $key.‘=>‘.$value.‘<br/>‘;
//注意这里要重新对$prices进行赋值,因为上一个foreach已经遍历完了
$prices=array(‘Tires‘=>100,‘Oil‘=>10,‘Spark Plugs‘=>4);
while($element =each($prices)){
echo $element[‘key‘];
echo ‘-‘;
echo $element[‘value‘];
echo ‘<br/>‘;
}
//用reset函数即可省去对$prices进行重新赋值了
reset($prices);
//这里相当于从$prices中获取$product中所对应的值
while(list($product,$price)=each($prices))
echo "$product - $price <br/>";
//建立多维数组
$products=array(array(‘TIR‘,‘Tires‘,100),array(‘OIL‘,‘oil‘,10)
,array(‘SPK‘,‘Spark Plugs‘,4));
for($row=0;$row<3;$row++){
for($col=0;$col<3;$col++){
echo ‘|‘.$products[$row][$col];
}
echo ‘|<br/>‘;
}
//关联多维数组
$products=array(array(‘Code‘=>‘TIR‘,‘Description‘=>‘Tires‘,‘Prices‘=>100),
array(‘Code‘=>‘OIL‘,‘Description‘=>‘Oil‘,‘Prices‘=>10),
array(‘Code‘=>‘SPK‘,‘Description‘=>‘Spark Plugs‘,‘Prices‘=>4));
for($row=0;$row<3;$row++){
echo ‘|‘.$products[$row][‘Code‘].‘|‘.$products[$row][‘Description‘].
‘|‘.$products[$row][‘Prices‘].‘<br/>‘;
}
for($row=0;$row<3;$row++){
while(list($key,$value)=each($products[$row])){
echo "|$value";
}
echo "|<br/>";
}
?>
实验效果:
二.数组的排序:
<?php
header("Content-Type:text/html;charset=utf8");
$products=array(‘Tires‘,‘Oil‘,‘Spark Plugs‘);
echo "原始序列<br/>";
for($i=0;$i<3;$i++) echo " $products[$i]";
echo ‘<br/>‘;
sort($products);
echo "常见排序<br/>";
for($i=0;$i<3;$i++) echo " $products[$i]";
echo ‘<br/><br/>‘;
$prices=array(‘Tires‘=>100,‘Oil‘=>10,‘Spark Plugs‘=>4);
echo "原始关联数组序列<br/>";
foreach($prices as $key => $value) echo $key.‘=>‘.$value.‘<br/>‘;
echo ‘<br/>‘;
echo "对value值排升序<br/>";
asort($prices);
foreach($prices as $key => $value) echo $key.‘=>‘.$value.‘<br/>‘;
echo ‘<br/>‘;
echo "对key值排升序<br/>";
ksort($prices);
foreach($prices as $key => $value) echo $key.‘=>‘.$value.‘<br/>‘;
echo ‘<br/>‘;
$products=array(array(‘TIR‘,‘Tires‘,100),array(‘OIL‘,‘oil‘,10)
,array(‘SPK‘,‘Spark Plugs‘,4));
echo "原始关联数组序列<br/>";
for($row=0;$row<3;$row++){
for($col=0;$col<3;$col++){
echo $products[$row][$col]." ";
}
echo ‘<br/>‘;
}
echo "<br/>";
function compare($x,$y){
if($x[1]==$y[1]) return 0;
else if($x[1]<$y[1]){
return -1;
}else{
return 1;
}
}
usort($products,‘compare‘);
echo "自定义排序<br/>";
for($row=0;$row<3;$row++){
for($col=0;$col<3;$col++){
echo $products[$row][$col]." ";
}
echo ‘<br/>‘;
}
?>
实验效果:
标签:
原文地址:http://www.cnblogs.com/xy95/p/5816360.html