教程分类

Product category

6.2、数组类型(索引数组、关联数组)

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

PHP 索引数组

有两种创建索引数组的方法:

索引是自动分配的(索引从 0 开始):

$cars=array("porsche","BMW","Volvo");

或者也可以手动分配索引:

$cars[0]="porsche";
$cars[1]="BMW";
$cars[2]="Volvo";

下面的例子创建名为 $cars 的索引数组,为其分配三个元素,然后输出包含数组值的一段文本:

实例

<?php
$cars=array("porsche","BMW","Volvo");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
<?php
$products = array("a", "b", "c");
var_dump($products);
?>
<?php
$numbers = range(1, 10);
$odds = range(1, 10, 2);
$letters = range("a", "z");
?> 
<?php
$products[0] = 0 ;
$products[3] = 3 ;
echo "$products[0] $products[3]";
?> 
<?php
for($i = 0;  $i < 10; $i++)
    $products[$i] = $i;
for($i = 0;  $i < 10; $i++)
    echo "$products[$i]";
?> 
<?php
for($i = 0;  $i < 10; $i++)
    $products[$i] = $i;
foreach( $products as $current)
    echo "$current";
?> 

PHP 关联数组

关联数组是使用您分配给数组的指定键的数组。

有两种创建关联数组的方法:

$age=array("Bill"=>"35","Steve"=>"37","Elon"=>"43");

或者:

$age['Bill']="63";
$age['Steve']="56";
$age['Elon']="47";

随后可以在脚本中使用指定键:

实例

<?php
$age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47");
echo "Elon is " . $age['Elon'] . " years old.";
?>
<?php
$prices = array("a" =>100, "b"=>10, "c"=>1);
var_dump($prices);
echo "<br>";
echo $prices["a"];
echo $prices["b"];
echo $prices["c"];
?>
<?php
$prices = array("a" =>100);
$prices["b"] = 10;
$prices["c"] = 1;

$prices["a"] = 100;
$prices["b"] = 10;
$prices["c"] = 1;
?> 
<?php
$prices = array("a" =>100, "b"=>10, "c"=>1);
foreach( $prices as $key => $value)
    echo $key.'=>'.$value.'<br />';
?> 
<?php
$prices = array("a" =>100, "b"=>10, "c"=>1);
while($element = each($prices)){
    echo $element['key'];
    echo '=>';
    echo $element['value'];
    echo '<br />';
}
?> 
<?php
$prices = array("a" =>100, "b"=>10, "c"=>1);
while(list($product, $price) = each($prices))
    echo "$product => $price<br />";
?> 
<?php
$prices = array("a" =>100, "b"=>10, "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.1、认识PHP数组 下一篇:6.3、定义PHP数组(简单数组、多维数组)