PHP数组

在本文中,我们展示了如何在PHP中使用数组。

$ php -v
php -v
PHP 8.1.2 (cli) (built: Aug  8 2022 07:28:23) (NTS)
...

我们使用PHP版本8.1.2。

PHP数组定义

数组是数据的集合。一个变量一次只能保存一项。数组可以容纳多个项目。

PHP有很多函数可以修改、排序、合并、切片、随机排列数组中的数据。有特定的数据库处理函数用于从数据库查询填充数组。其他几个函数返回数组。

PHP数组初始化

数组可以用一对[]括号和array函数来初始化。

<?php

$names = ["Jane", "Lucy", "Timea", "Beky", "Lenka"];

print_r($names);

我们创建了一个$names数组,其中存储了五个女性名字。print_r函数打印了有关该变量的人类可读信息。

$ php init1.php
Array
(
    [0] => Jane
    [1] => Lucy
    [2] => Timea
    [3] => Beky
    [4] => Lenka
)

从输出中我们可以看到我们可以访问它们的名称和它们的索引。

传统上,数组是用array函数初始化的。在其最简单的形式中,该函数采用任意数量的逗号分隔值。

<?php

$names = array("Jane", "Lucy", "Timea", "Beky", "Lenka");

print_r($names);

使用array函数创建相同的女性名字数组。

可以通过为数组索引赋值来初始化数组。

<?php

$continents[0] = "America";
$continents[1] = "Africa";
$continents[2] = "Europe";
$continents[3] = "Asia";
$continents[4] = "Antarctica";
$continents[5] = "Australia";

print_r($continents);

我们通过为数组索引赋值来创建$continents数组。“美国”的索引为0,“欧洲”的索引为2等。

<?php

$continents = [ 1 => "America", 2 => "Africa",
    3 => "Europe", 4 => "Asia", 5 => "Antarctica",
    6 => "Australia" ];

print_r($continents);

在此示例中,我们创建了具有指定索引的$continents数组。默认情况下,第一个索引为零。在我们的例子中,我们从1开始。

$ php init4.php
Array
(
    [1] => America
    [2] => Africa
    [3] => Europe
    [4] => Asia
    [5] => Antarctica
    [6] => Australia
)

现在我们有一个大洲数组,其中包含我们选择的索引。

索引不必是连续的数字。

<?php

$languages[10] = "PHP";
$languages[20] = "Python";
$languages[30] = "Ruby";
$languages[40] = "PERL";
$languages[50] = "Java";

print_r($languages);

在示例中,我们选择了数字10、20、30、40和50作为$languages数组的索引。

当我们对PHP数组进行赋值初始化时,我们可以省略索引。PHP自动为我们创建索引。

<?php

$actors[] = "Philip Seymour Hoffman";
$actors[] = "Tom Cruise";
$actors[] = "Bill Paxton";
$actors[] = "Adrien Brody";
$actors[] = "Daniel Craig";

print_r($actors);

创建了一个actors数组。没有设置具体指标。

$ php init6.php
Array
(
    [0] => Philip Seymour Hoffman
    [1] => Tom Cruise
    [2] => Bill Paxton
    [3] => Adrien Brody
    [4] => Daniel Craig
)

PHP解释器创建了从零开始的连续索引。

<?php

$novels[10] = "Doctor Zhivago";
$novels[11] = "War and Peace";
$novels[] = "In Cold Blood";
$novels[20] = "Crime and Punishment";
$novels[] = "Catch XII";

print_r($novels);

在这个脚本中,我们省略了两个索引。PHP将添加它们。它将创建索引12和索引21。

$ php init5.php
Array
(
    [10] => Doctor Zhivago
    [11] => War and Peace
    [12] => In Cold Blood
    [20] => Crime and Punishment
    [21] => Catch XII
)

PHP已自动创建索引12和21。

数组的键也可以是字符串。

<?php

$countries = [
    "de" => "Germany", "sk" => "Slovakia",
    "us" => "United States", "ru" => "Russia",
    "hu" => "Hungaria", "pl" => "Poland" ];

echo $countries["de"] . "\n";
echo $countries["sk"] . "\n";

我们创建一个带有字符串索引的$countries数组。

$ php init8.php
Germany
Slovakia

PHP数组元素类型

PHP数组可以包含各种类型的元素。

<?php 

$vals = ['sky', true, -4, [1, 2, 3, 4]];

foreach ($vals as $val) {
    
    $t = gettype($val);

    $res = match($t) {

        'string' => 'value is a string',
        'integer' => 'value is an integer',
        'boolean' => 'value is a boolean', 
        'array' => 'value is an array',
        default => 'unknown type'
    };

    echo "$res\n";

}

在示例中,我们有一个包含不同类型元素的数组。通过匹配表达式和gettype函数,我们可以获取每个元素的类型。

$ php types.php 
value is a string
value is a boolean
value is an integer
value is an array

PHP细读数组

接下来我们读取数组的内容。我们可以通过多种方式显示数组中的数据。

<?php

$languages[10] = "PHP";
$languages[20] = "Python";
$languages[30] = "Ruby";
$languages[40] = "PERL";
$languages[50] = "Java";

echo $languages[10], "\n";
echo $languages[20], "\n";
echo $languages[30], "\n";
echo $languages[40], "\n";
echo $languages[50], "\n";

我们可以通过索引访问数组中的数据。

$ php peruse1.php
PHP
Python
Ruby
PERL
Java

我们已将所有五种语言打印到控制台。

<?php

$continents = [ "America", "Africa", "Europe",
    "Asia", "Australia", "Antarctica" ];

$len = count($continents);

for ($i = 0; $i < $len; $i++) {
    echo $continents[$i], "\n";
}

在这个例子中,我们使用for语句来细读一个$continents数组。

$len = count($continents);

首先,我们使用count函数计算数组中元素的数量。

for ($i = 0; $i < $len; $i++) {
    echo $continents[$i], "\n";
}

for循环打印数组中索引为0..$len-1的元素。

<?php

$continents = [ "America", "Africa", "Europe", "Asia",
    "Australia", "Antarctica" ];

foreach ($continents as $continent) {
    echo $continent, "\n";
}

细读数组的最简单方法是使用foreach语句。该语句逐一遍历数组并将当前元素放入临时$continent变量。它在不使用索引或键的情况下访问数据。

<?php

$countries = [ "de" => "Germany", "sk" => "Slovakia",
    "us" => "United States", "ru" => "Russia",
    "hu" => "Hungaria", "pl" => "Poland" ];

function show_values($value, $key) {

    echo "The $key stands for the $value\n";
}

array_walk($countries, 'show_values');

在最后一个例子中,我们使用array_walk函数来读取一个数组。它将用户函数应用于数组的每个成员。用户函数将项的键和值作为参数。

$ php walk.php
The de stands for the Germany
The sk stands for the Slovakia
The us stands for the United States
The ru stands for the Russia
The hu stands for the Hungary
The pl stands for the Poland

我们在句子中将键和值都打印到控制台。

PHP数组排序

首先我们要对数组进行排序。

<?php

$names = [ "Jane", "Rebecca", "Lucy", "Lenka", "Ada" ];

echo "Unsorted: \n";

foreach ($names as $name) {
    echo "$name ";
}

echo "\n";

sort($names);

echo "Sorted: \n";

foreach ($names as $name) {
    echo "$name ";
}

echo "\n";

在上面的脚本中,我们有一个$names数组。我们使用sort函数对数组的内容进行排序。

$ php sort.php
Unsorted:
Jane Rebecca Lucy Lenka Ada
Sorted:
Ada Jane Lenka Lucy Rebecca

脚本的输出显示未排序和排序的女性名字。

rsort函数对数组进行倒序排序。

<?php

$numbers = [ 12, 3, 5, 1, 6, 7, 10, 0, 9, 8, 11];

sort($numbers);

echo "Ascending order: \n";

foreach ($numbers as $n) {
    echo "$n ";
}

echo "\n";

rsort($numbers);

echo "Descending order: \n";

foreach ($numbers as $n) {
    echo "$n ";
}

echo "\n";

有一个整数数组。它按升序和降序排序。

sort($numbers);

sort函数按升序对整数进行排序。

rsort($numbers);

rsort函数按降序对整数进行排序。

$ php sort2.php
Ascending order:
0 1 3 5 6 7 8 9 10 11 12
Descending order:
12 11 10 9 8 7 6 5 3 1 0

在下面的示例中,我们展示了如何对重音字符进行排序。

<?php

setlocale(LC_ALL, 'sk_SK.utf8');

$words = [ "ďateľ", "auto", "železo", "byt", "kocka", "dáma",
    "zem", "autor", "ceduľa", "čižma"];

sort($words, SORT_LOCALE_STRING);

echo "Ascending order: \n";

foreach ($words as $w) {
    echo "$w ";
}

echo "\n";

rsort($words, SORT_LOCALE_STRING);

echo "Descending order: \n";

foreach ($words as $w) {
    echo "$w ";
}

echo "\n";

我们有一组包含特定重音的斯洛伐克语单词。

setlocale(LC_ALL, 'sk_SK.utf8');

我们使用setlocale函数设置斯洛伐克语言环境。语言环境代表特定的地理、政治或文化区域。

$words = [ "ďateľ", "auto", "železo", "byt", "kocka", "dáma",
    "zem", "autor", "ceduľa", "čižma"];

$words是一组带重音的斯洛伐克语单词。

sort($words, SORT_LOCALE_STRING);

我们使用sort函数对数组进行升序排序。我们将SORT_LOCALE_STRING标志传递给该函数,它告诉sort将区域设置考虑在内。

$ php locale_sort.php
Ascending order:
auto autor byt ceduľa čižma dáma ďateľ kocka zem železo
Descending order:
železo zem kocka ďateľ dáma čižma ceduľa byt autor auto

单词已根据斯洛伐克标准正确排序。

有时我们需要进行自定义排序。对于自定义排序,我们在PHP中有usort函数。

<?php

$names = [ "Michael Brown", "Albert Einstein", "Gerry Miller",
    "Tom Willis", "Michael Gray", "Luke Smith" ];

function sort_second_names($a, $b) {

    $name1 = explode(" ", $a);
    $name2 = explode(" ", $b);

    return strcmp($name1[1], $name2[1]);
}

usort($names, 'sort_second_names');

foreach ($names as $name) {
    echo "$name\n";
}

echo "\n";

我们有一个全名数组。sort函数将根据名字对这些字符串进行排序,因为它们在第二个名字之前。我们创建了一个解决方案,根据名字对这些名字进行排序。

function sort_second_names($a, $b) {

    $name1 = explode(" ", $a);
    $name2 = explode(" ", $b);

    return strcmp($name1[1], $name2[1]);
}

我们有自定义排序功能。名称由explode函数拆分,第二个名称与strcmp函数进行比较。

usort($names, 'sort_second_names');

usort函数接受比较函数作为它的第二个参数。

$ php custom_sorting.php
Michael Brown
Albert Einstein
Michael Gray
Gerry Miller
Luke Smith
Tom Willis

名称已根据他们的名字正确排序。

PHP计算数组中的值

count函数计算数组中元素的数量。array_sum函数计算所有值的总和。array_product函数计算数组中值的乘积。

<?php

$numbers = [ 1, 2, 4, 5, 2, 3, 5, 2 ];

$len = count($numbers);
$sum = array_sum($numbers);
$prod = array_product($numbers);

echo "In the array, there are $len numbers\n";
echo "The sum of the numbers is $sum\n";
echo "The product of the numbers is $prod\n";

在示例中,我们有一个数字数组。我们在数组上应用上面定义的函数。

$ php counting.php
In the array, there are 8 numbers
The sum of the numbers is 24
The product of the numbers is 2400

PHP唯一值

在下面的示例中,我们找出数组中的唯一值。

<?php

$numbers = array(3, 4, 4, 3, 2, 4);
$count_values = array_count_values($numbers);

print_r($count_values);

$unique = array_unique($numbers);

print_r($unique);

在这个脚本中,我们在数组中有重复项。array_count_values函数返回一个数组,其中包含每个值的出现次数。array_unique函数返回一个没有重复的数组。

$ php unique.php
Array
(
    [3] => 2
    [4] => 3
    [2] => 1
)
Array
(
    [0] => 3
    [1] => 4
    [4] => 2
)

第一个数组表示3出现了两次,4出现了三次,2出现了一次。第二个数组表示数组中存在三个值:3、4和2。值3的索引为0,4的索引为1,2的索引为4。array_unique函数保持索引不变.

PHP切片数组

array_slice函数返回一个数组中的元素序列,该序列由其偏移量和长度参数指定。

<?php

$nums = range(1, 20);

$slice1 = array_slice($nums, 0, 3);

echo "Slice1:\n";

foreach ($slice1 as $s) {

    echo "$s ";
}

echo "\n";

$slice2 = array_slice($nums, -3);

echo "Slice2:\n";

foreach ($slice2 as $s) {

    echo "$s ";
}

echo "\n";

在示例中,我们创建了一个整数数组的两个切片。

$slice1 = array_slice($nums, 0, 3);

我们从第一个元素开始创建一个切片;切片的长度是三个元素。

$slice2 = array_slice($nums, -3);

通过给出负偏移量​​,切片从数组的末尾开始创建。

$ php slicing.php
Slice1:
1 2 3
Slice2:
18 19 20

PHP数组指针

PHP有一个内部数组指针。在下面的示例中,我们展示了操作此指针的函数。

<?php

$continents = [ "America", "Africa", "Europe", "Asia", "Australia",
    "Antarctica" ];

$item1 = current($continents);
$item2 = next($continents);
$item3 = next($continents);
$item4 = end($continents);
$item5 = prev($continents);

echo "$item1, $item2, $item3, $item4, $item5\n";

reset($continents);

while(list($idx, $val) = each($continents)) {

    echo "Index: $idx, Value: $val\n";
}

在这个例子中,我们使用移动内部数组指针的函数遍历数组。

$item1 = current($continents);
$item2 = next($continents);
$item3 = next($continents);
$item4 = end($continents);
$item5 = prev($continents);

current函数返回数组中的当前元素。一开始,它是数组的第一个元素。next函数将指针前进一个位置。end函数返回最后一个元素。prev元素返回元素,当前元素之前的一个位置。在我们的例子中,它是最后一个元素的下一个。

reset($continents);

while(list($idx, $val) = each($continents)) {

    echo "Index: $idx, Value: $val\n";
}

这里我们使用reset函数再次将内部指针设置为第一个元素并再次细读$continents数组。

$ php array_pointer.php
America, Africa, Europe, Antarctica, Australia
Index: 0, Value: America
Index: 1, Value: Africa
Index: 2, Value: Europe
Index: 3, Value: Asia
Index: 4, Value: Australia
Index: 5, Value: Antarctica

PHP合并数组

array_merge函数合并数组。

<?php

$names1 = [ "Jane", "Lucy", "Rebecca" ];
$names2 = [ "Lenka", "Timea", "Victoria" ];

$names = array_merge($names1, $names2);

foreach ($names as $name) {

    echo "$name ";
}

echo "\n";

在这个例子中,我们有两个数组:$names1$names2。我们使用array_merge函数来创建$names数组通过合并前两个数组。

$ php merge.php
Jane Lucy Rebecca Lenka Timea Victoria

新数组有六个名字。

PHP修改数组

可以使用array_pusharray_poparray_shiftarray_unshift函数修改PHP数组。

<?php

$numbers = [ 1, 2, 3, 4 ];

array_push($numbers, 5, 6);

foreach ($numbers as $num) {
    echo $num, " ";
}

echo "\n";

array_pop($numbers);

foreach ($numbers as $num) {
    echo $num, " ";
}

echo "\n";

array_unshift($numbers, -1, 0);

foreach ($numbers as $num) {
    echo $num, " ";
}

echo "\n";

array_shift($numbers);

foreach ($numbers as $num) {
    echo $num, " ";
}

echo "\n";

在上面的脚本中,我们使用了修改数组内容的函数。我们有一个包含4个数字的$numbers数组:1、2、3和4。

array_push($numbers, 5, 6);

array_push函数将一个或多个项目插入到数组的末尾。我们的数组现在包含值1、2、3、4、5和6。

array_pop($numbers);

array_pop函数从数组中删除最后一项。我们的数组现在存储数字1、2、3、4和5。

array_unshift($numbers, -1, 0);

array_unshift函数将-1和0添加到数组的开头。该数组包含值-1、0、1、2、3、4和5。

array_shift($numbers);

最后,array_shift函数从数组中删除第一项。现在数组中有值0、1、2、3、4和5。

$ php modify.php
1 2 3 4 5 6
1 2 3 4 5
-1 0 1 2 3 4 5
0 1 2 3 4 5

PHP范围函数

range函数通过自动创建元素序列来简化数组创建。它接受三个参数:序列开始、序列结束和一个可选的增量,默认为1。

<?php

$numbers1 = range(1, 15);

foreach ($numbers1 as $num) {
    echo "$num ";
}

echo "\n";

$numbers2 = range(15, 1, -1);

foreach ($numbers2 as $num) {
    echo "$num ";
}

echo "\n";

range函数使我们能够轻松地创建连续数字列表。

$numbers1 = range(1, 15);

创建了一个包含数字1、2、…15的数组。

$numbers2 = range(15, 1, -1);

可以通过指定负增量来创建值的降序列。

$ php range.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

PHP随机化数组值

array_rand函数从数组中随机选取一个或多个条目。shuffle函数随机化数组中元素的顺序。

<?php

$nums = range(1, 20);

echo ($nums[array_rand($nums)]) . "\n";

$r = array_rand($nums, 2);
echo $nums[$r[0]] . "\n";
echo $nums[$r[1]] . "\n";

shuffle($nums);

foreach ($nums as $n) {
    echo "$n ";
}

echo "\n";

在示例中,我们从数组中选取随机值并随机化其元素顺序。

echo ($nums[array_rand($nums)]) . "\n";

array_rand函数从$num数组中返回一个随机键。

$r = array_rand($nums, 2);

在这种情况下,array_rand函数返回两个随机键的数组。

$ php randomize.php
4
2
19
13 19 4 3 17 11 20 16 10 9 8 14 15 12 18 2 6 5 1 7

这是randomize.php程序的示例输出。

PHPin_array函数

in_array函数检查特定元素是否在数组中

<?php

$names = [ "Jane", "Adriana", "Lucy", "Rebecca" ];

if (in_array("Jane", $names)) {
    echo "Jane is in the array\n";
} else {
    echo "Jane is not in the array\n";
}

if (in_array("Monica", $names)) {
    echo "Monica is in the array\n";
} else {
    echo "Monica is not in the array\n";
}

我们的脚本检查’Jane’和’Monica’是否在$names数组中。

$ php inarray.php
Jane is in the array
Monica is not in the array

‘Jane在数组中,但’Monica’不在。

PHP数组键和值

PHP数组是由键值对组成的关联数组。

<?php

$domains = [ "sk" => "Slovakia", "de" => "Germany",
    "hu" => "Hungary", "ru" => "Russia" ];

$keys = array_keys($domains);
$values = array_values($domains);

foreach ($keys as $key) {
    echo "$key ";
}

echo "\n";

foreach ($values as $value) {
    echo "$value ";
}

echo "\n";

array_keys函数返回数组的所有键。array_values函数返回数组的所有值。

$ php keysvalues.php
sk de hu ru
Slovakia Germany Hungary Russia

第一行由顶级域名组成。这些是$domains数组的键。第二行是相应国家的名称。这些是数组的值。

PHParray_walk函数

array_walk函数将用户定义的函数应用于数组的每个成员。

<?php

$countries = [ "de" => "Germany", "sk" => "Slovakia",
    "us" => "United States", "ru" => "Russia",
    "hu" => "Hungaria", "pl" => "Poland" ];

function show_values($value, $key) {

    echo "The $key stands for the $value\n";
}

array_walk($countries, 'show_values');

我们有一个$countries数组。我们将show_values函数应用于数组的每个元素。这些函数只是打印每个元素的键和值。

$ php array_walk.php
The de stands for the Germany
The sk stands for the Slovakia
The us stands for the United States
The ru stands for the Russia
The hu stands for the Hungaria
The pl stands for the Poland

在本文中,我们介绍了PHP数组。

列出所有PHP教程。

赞(0) 打赏

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏