码迷,mamicode.com
首页 > 编程语言 > 详细

php之数组

时间:2016-08-29 00:06:37      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

一数组的建立以及输出

<?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/>‘;
}

?>

实验效果:

技术分享

 

php之数组

标签:

原文地址:http://www.cnblogs.com/xy95/p/5816360.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!