Home > php教程 > php手册 > body text

PHP 数组之PHP基础入门教程

WBOY
Release: 2016-06-13 10:17:09
Original
1019 people have browsed it

本文章来给各位同学详细介绍关于PHP 数组之PHP基础入门教程,各位有需要学习php数组使用的朋友可进入参考。

什么是数组?
在使用 PHP 进行开发的过程中,或早或晚,您会需要创建许多相似的变量。

无需很多相似的变量,你可以把数据作为元素存储在数组中。

数组中的元素都有自己的 ID,因此可以方便地访问它们。

有三种数组类型:
数值数组
带有数字 ID 键的数组
关联数组
数组中的每个 ID 键关联一个值
多维数组
包含一个或多个数组的数组
数值数组
数值数组存储的每个元素都带有一个数字 ID 键。

可以使用不同的方法来创建数值数组:

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

 代码如下 复制代码

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

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

 代码如下 复制代码

$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";可以在脚本中使用这些 ID 键:

$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 键:

 代码如下 复制代码

$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
  )
)

例子 2
让我们试着显示上面的数组中的一个单一的值:

 代码如下 复制代码

echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?";

以上代码的输出:

Is Megan a part of the Griffin family?

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!