教程分类

Product category

6.4、使用数组(输出数组、统计元素个数、遍历数组、转换数组、数组排序、数组指针)

编辑:57自学网 发布日期:2019-11-29 17:29
  • 高清线路
  • 备用线路
  • 图文解说

6.4.1输出数组

<?php
$prices = array("a" =>100, "b"=>10, "c"=>1);
print_r($prices);
var_dump($prices);
?>

6.4.2 统计元素个数

<?php
$a[0] = 1;
$a[3] = 3;
$a[6] = 5;
echo count($a);
?>

<?php
$products = array(array( 'TIR', 'Tires', 100),
               array( 'OIL', 'oil', 10),
               array( 'SPK', 'Spark Plugs', 4));
 echo count($products, 1);
?>

6.4.3 遍历数组

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
var_dump($arr);
// $arr is now array(2, 4, 6, 8)
unset($value); // 最后取消掉引用
?>


<?php
$prices["a"] = 100;
$prices["b"] = 10;
$prices["c"] = 1;
while(list($product, $price) = each($prices))
    echo "$product => $price<br />";
?> 


<?php
$prices["a"] = 100;
$prices["b"] = 10;
$prices["c"] = 1;
while(list($product, $price) = each($prices))
    echo "$product => $price<br />";
reset($prices) ;
while(list($product, $price) = each($prices))
    echo "$product => $price<br />";
?> 

6.4.4数组与字符串的转换

<?php
$php  = "PHP is a popular general-purpose scripting language";
$php1 = explode(" ", $php);
var_dump($php1);
?>


<?php
$array = array('ASP', 'PHP', 'JSP');
$str = implode(",", $array);
echo $str; 
?>

6.4.5 数组排序

<?php
$products = array( "Tires", "Oil", "Spark Plugs" );
sort($products);
print_r($products);
?>

<?php
$prices = array( 100, 10, 4 );
sort($prices);
print_r($prices);
?>


<?php
$prices = array( "Tires"=>100, "Oil"=>10, "Spark Plugs"=>4 );
asort($prices);
print_r($prices);
?>


<?php
$prices = array( "Tires"=>100, "Oil"=>10, "Spark Plugs"=>4 );
ksort($prices);
print_r($prices);
?>


<?php
$products = array( array( "TIR", "Tires", 100 ), 
          array( "OIL", "Oil", 10 ),
          array( "SPK", "Spark Plugs", 4 ) );
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");
print_r($products);
?>


<?php
$products = array( array( "TIR", "Tires", 100 ), 
          array( "OIL", "Oil", 10 ),
          array( "SPK", "Spark Plugs", 4 ) );
function compare($x, $y){ 
    if ( $x[2] == $y[2] )
        return 0;
    else if ( $x[2] < $y[2] )
        return -1;
    else
        return 1;
}
usort($products, "compare");
print_r($products);
?>


<?php
$products = array( array( "TIR", "Tires", 100 ), 
          array( "OIL", "Oil", 10 ),
          array( "SPK", "Spark Plugs", 4 ) );
function reverseCompare($x, $y){ 
    if ( $x[2] == $y[2] )
        return 0;
    else if ( $x[2] < $y[2] )
        return 1;
    else
        return -1;
}
usort($products, "compare");
print_r($products);
?>

6.4.6 数组指针

<?php
$array = array(1, 2, 3);
$value = end($array);
while ($value){ 
    echo "$value<br>";
    $value = prev($array);
}
?>
上一篇:6.3、定义PHP数组(简单数组、多维数组) 下一篇:6.5、PHP操作元素(查询指定、获取、添加、删除元素)