PHP =>

WBOY
Release: 2016-06-13 13:05:41
Original
905 people have browsed it

PHP =>



例子 1

在这个例子中,会自动分配 ID 键:

$names = array("Peter","Quagmire","Joe");

例子 2

在这个例子中,我们人工分配的 ID 键:

$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";

可以在脚本中使用这些 ID 键:

<?php

$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";

echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors";
?>

以上代码的输出:

Quagmire and Joe are Peter's neighbors

关联数组

关联数组,它的每个 ID 键都关联一个值。

在存储有关具体命名的值的数据时,使用数值数组不是最好的做法。

通过关联数组,我们可以把值作为键,并向它们赋值。
例子 1

在本例中,我们使用一个数组把年龄分配给不同的人:

$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

例子 2

本例与例子 1 相同,不过展示了另一种创建数组的方法:

$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";

可以在脚本中使用 ID 键:

<?php

$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";

echo "Peter is " . $ages['Peter'] . " years old.";
?>

以上脚本的输出:

Peter is 32 years old.

多维数组

在多维数组中,主数组中的每个元素也是一个数组。在子数组中的每个元素也可以是数组,以此类推。
例子 1

在本例中,我们创建了一个带有自动分配的 ID 键的多维数组:

$families = array
(
  "Griffin"=>array
  (
  "Peter",
  "Lois",
  "Megan"
  ),
  "Quagmire"=>array
  (
  "Glenn"
  ),
  "Brown"=>array
  (
  "Cleveland",
  "Loretta",
  "Junior"
  )
);

如果输出这个数组的话,应该类似这样:

Array
(
[Griffin] => Array
  (
  [0] => Peter
  [1] => Lois
  [2] => Megan
  )
[Quagmire] => Array
  (
  [0] => Glenn
  )
[Brown] => Array
  (
  [0] => Cleveland
  [1] => Loretta
  [2] => Junior
  )
)












Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template