📅  最后修改于: 2020-10-21 05:07:02             🧑  作者: Mango
数组是一种数据结构,它在一个值中存储一个或多个相似类型的值。例如,如果要存储100个数字,则可以轻松定义100个长度的数组,而不是定义100个变量。
共有三种不同类型的数组,每个数组值都使用一个称为数组索引的ID c进行访问。
数字数组-具有数字索引的数组。值以线性方式存储和访问。
关联数组-以字符串为索引的数组。这将元素值与键值相关联地存储,而不是按照严格的线性索引顺序存储。
多维数组-使用多个索引访问包含一个或多个数组和值的数组
注–函数参考PHP Array Functions中提供了内置的数组函数
这些数组可以存储数字,字符串和任何对象,但是它们的索引将由数字表示。默认情况下,数组索引从零开始。
以下是显示如何创建和访问数字数组的示例。
在这里,我们使用array()函数创建数组。该函数在函数参考中进行了说明。
";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value ) {
echo "Value is $value
";
}
?>
这将产生以下结果-
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
关联数组在功能上与数字数组非常相似,但是它们的索引不同。关联数组将其索引作为字符串,以便您可以在键和值之间建立牢固的关联。
要将员工的薪水存储在一个数组中,数字索引数组不是最佳选择。取而代之的是,我们可以将员工姓名用作关联数组中的键,而值将是其各自的薪水。
注意-打印时不要将关联数组保留在双引号内,否则它将不会返回任何值。
2000, "qadir" => 1000, "zara" => 500);
echo "Salary of mohammad is ". $salaries['mohammad'] . "
";
echo "Salary of qadir is ". $salaries['qadir']. "
";
echo "Salary of zara is ". $salaries['zara']. "
";
/* Second method to create array. */
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of mohammad is ". $salaries['mohammad'] . "
";
echo "Salary of qadir is ". $salaries['qadir']. "
";
echo "Salary of zara is ". $salaries['zara']. "
";
?>
这将产生以下结果-
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low
多维数组主数组中的每个元素也可以是数组。子数组中的每个元素可以是一个数组,依此类推。使用多个索引访问多维数组中的值。
在此示例中,我们创建一个二维数组来存储三个学科中三个学生的成绩-
本示例是一个关联数组,您可以以相同的方式创建数字数组。
array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "
";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "
";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "
";
?>
这将产生以下结果-
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39