php 数组添加数组

tech2023-11-29  38

php 数组添加数组

Many things that make the world as we know it possible are so commonplace that we forget they even exist. One of my favorite examples is the elevator; the idea of a lifting platform or box is very old but it had to wait for the Industrial Revolution to become a practical device. When Mr. Otis installed his first successful elevator in the brand-new E. V. Haughwout Building in 1857, he opened the path for the vertical growth of metropolises like New York City and São Paulo.

使我们所知道的世界成为可能的许多事物是如此普遍,以至于我们忘记了它们甚至存在。 我最喜欢的例子之一是电梯。 起重平台或箱子的想法很老,但必须等待工业革命成为实用的设备。 奥蒂斯先生于1857年在崭新的EV Haughwout大楼中安装了他的第一个成功的电梯时,他为纽约和圣保罗等大都市的垂直发展开辟了道路。

Another favorite invention of mine are tables. Not of the dining sort, though they too are immensely important both for eating and working, rather the type that stores information. Such tables are part of our daily life in hundreds of different variations. In many countries, milk, butter and cereal containers display a table of nutritional values – though I wonder who reads and understands them. Most papers, for those that still read them in print, are organized as a sort of table. Many cities, especially in the New World (herein extended to include Australia and New Zealand), are organized as a table with streets as rows and avenues as columns. Children start out with tables as soon as they begin to learn multiplication and divisions; in fact, Portuguese has an interesting word for multiplication tables: taboada, roughly, “a thing put on a table!” Engineering is unthinkable without tables, and tables are the backbones of management techniques like Operational Research and Game Theory.

我的另一个最喜欢的发明是桌子。 尽管它们对于饮食和工作都非常重要,但不是用于存储食物的类型,而是用于存储信息的类型。 这些表是数百种不同形式的日常生活的一部分。 在许多国家/地区,牛奶,黄油和谷物容器显示了营养价值表-尽管我想知道是谁阅读和理解它们的。 对于那些仍在打印中阅读的论文,大多数论文都是按照表格的形式组织的。 许多城市,特别是在新世界(在此扩展到包括澳大利亚和新西兰)中,都被组织成一张桌子,街道成行,大道成列。 孩子们一旦开始学习乘法和除法,便会从桌子开始。 实际上,葡萄牙语在乘法表中有一个有趣的词: taboada ,大概是“放在桌子上的东西!” 没有表格,工程是不可想象的,表格是诸如运筹学和博弈论这样的管理技术的骨干。

But what about the subject of this article, arrays?

但是,本文的主题数组呢?

什么是数组? (What are Arrays?)

Tables organize data in such a way that we can easily find correlations or perform straightforward computations. An array is essentially a way to organize data in a table-like manner. The name “array” comes from the same Latin roots as the word “arrangement.”

表以一种组织数据的方式,使我们可以轻松地找到相关性或执行简单的计算。 数组本质上是一种以表形式组织数据的方法。 名称“数组”与“排列”一词源于拉丁语。

To help us understand arrays better, let’s begin with a table called Prices NYC to show the price of a hamburger in New York City is one dollar:

为了帮助我们更好地理解数组,让我们从一个名为“ Prices NYC”的表开始,以显示纽约市一个汉堡包的价格为一美元:

We can write it as an array called, you’d never guess, pricesNYC:

我们可以将其编写为一个数组,您永远不会猜到, pricesNYC :

pricesNYC ("hamburger"=1)

That piece of information is so simple that representing it on a table or an array seems a waste of time. But what if we add the price of a side of fries? We could write:

该信息是如此简单,以至于在表或数组上表示它似乎是在浪费时间。 但是,如果我们加上炸薯条的价格怎么办? 我们可以这样写:

and:

和:

pricesNYC ("hamburger"=1, "fries"=.70)

This is an associative array. In an associative array, each and every value is identified by a label, or sequence of labels, called a key. hamburger and fries are the keys in this example, and their values are 1 and .70 respectively. Keys can also be a numerical sequence instead of labels. In such cases the array is said to be non-associative. Our example as a non-associative array would be:

这是一个关联数组 。 在关联数组中,每个值都由称为键的标签或标签序列标识。 汉堡和薯条是此示例中的关键,它们的值分别为1和.70。 键也可以是数字序列而不是标签。 在这种情况下,该数组被称为是非关联数组。 我们作为非关联数组的示例为:

pricesNYC (0=1, 1=.70)

The value at index (or key) 0 is 1 and the value at index 1 is .70. (In most programming languages, non-associative arrays start with an index of 0 for largely historical and mathematically convenient reasons.)

索引(或键)0处的值为1,索引1处的值为.70。 (在大多数编程语言中,出于很大程度上历史和数学上的方便原因,非关联数组以索引0开头。)

Sometimes the indexes are not explicitly given but the values are still accessible by their position.

有时未明确给出索引,但仍可以通过其位置访问这些值。

pricesNYC (1, .70)

Sticking with the associative array, we could create a second table and array if we want to show the same prices for Los Angeles:

坚持使用关联数组,如果我们想显示洛杉矶的相同价格,我们可以创建第二个表和数组:

pricesLA ("hamburger"=1.30, "fries"=.50)

Alternatively, we could combine the data from the two tables together like this:

另外,我们可以将两个表中的数据合并在一起,如下所示:

prices ("New York"=pricesNYC ("hamburger"=1, "fries"=.70), "Los Angeles"=pricesLA ("hamburger"=1.30, "fries"=.50))

We’ve begin to create arrays within arrays and each value is now identified by the sequence of labels. For example, the key for the price of a burger in NYC is now New York, hamburger. In prices, the top-level array has two keys, New York and Los Angeles. Each of these keys point to values that are actually other arrays. These second-level arrays have the labels hamburger and fries which finally point to a number which is the desired price.

我们已经开始在数组中创建数组,并且每个值现在都由标签序列标识。 例如,纽约市汉堡价格的键现在是纽约 汉堡 。 在prices ,顶层阵列具有两个关键要素,即纽约和洛杉矶 。 这些键中的每一个都指向实际上是其他数组的值。 这些二级数组的标签为汉堡包和炸薯条 ,这些标签最终指向所需价格的数字。

In a non-associative fashion, the array would look something like this:

以非关联的方式,数组看起来像这样:

prices (0=pricesNYC (0=1, 1=.70), 1=pricesLA (0=1.30, 1=.50))

The price of a burger in NYC is found here with the index 0 0.

在纽约可以找到一个汉堡的价格,索引为0 0。

创建数组 (Creating Arrays)

Now that the concept of arrays is established, let’s move on to discussing how PHP implements them and, more importantly, how we can create them. The most orthodox method of creating an array is to use the array() construct:

现在已经建立了数组的概念,让我们继续讨论PHP如何实现它们,更重要的是,我们如何创建它们。 创建数组的最传统的方法是使用array()构造:

<?php $pricesNYC = array();

Our array as created is empty. We can then assign values to the array using the key specified in brackets:

创建的数组为空。 然后,我们可以使用方括号中指定的键将值分配给数组:

<?php $pricesNYC["hamburger"] = 1; $pricesNYC["fried"] = .70;

Alternatively we could have populated the array at the same time we create it using the syntax key => value. The key/value pairs are separated by comma:

或者,我们可以在使用语法key => value创建数组的同时填充数组。 键/值对以逗号分隔:

<?php $pricesNYC = array("hamburger" => 1, "fries" => .70);

When I was first learning PHP, I often had to go back to the documentation to check whether the correct operator was => or ->. One day I came up with the mnemonic “this key will be equal to that value” and now I easily remember => is the correct choice.

当我第一次学习PHP时,经常不得不回到文档中检查正确的运算符是=>还是-> 。 有一天,我想出了一个助记符“此键等于该值”,现在我容易记得=>是正确的选择。

So what do the above examples look like for non-associative arrays?

那么,以上示例对于非关联数组是什么样的?

<?php $pricesNYC = array(); $pricesNYC[0] = 1; $pricesNYC[1] = .70;

and:

和:

<?php $pricesNYC = array(0 => 1, 1 => .70);

If all you want is a non-associative array, it isn’t necessary to specify the index. PHP automatically uses the next integer value in the key sequence, starting at 0, for key if you do not provide one. These examples produce identical non-associative arrays to those we just saw:

如果您想要的只是一个非关联数组,则无需指定索引。 如果您不提供键,PHP会自动使用键序列中的下一个整数值(从0开始)作为键。 这些示例产生与我们刚刚看到的相同的非关联数组:

<?php $pricesNYC = array(); $pricesNYC[] = 1; $pricesNYC[] = .70;

and:

和:

<?php $pricesNYC = array(1, .70);

PHP arrays can have mixed keys, that is, some keys can be strings and other can be indexes. So far we’ve seen keys that were either strings (like hamburger) and integers (0).

PHP数组可以具有混合键,即某些键可以是字符串,而另一些可以是索引。 到目前为止,我们已经看到了既可以是字符串(例如hamburger )又可以是整数(0)的键。

Now let’s make things a little more interesting by transforming the two-city table into an array. The creation of the empty array is, as before, straightforward:

现在,通过将两个城市的表转换为数组,使事情变得更加有趣。 如前所述,空数组的创建非常简单:

<?php $prices = array();

Also straightforward is how the array can be populated with the brackets syntax:

同样简单的是如何使用方括号语法填充数组:

<?php $prices["New York"]["hamburger"] = 1; $prices["New York"]["fries"] = 0.70; $prices["Los Angeles"]["hamburger"] = 1.30; $prices["Los Angeles"]["fries"] = 0.50;

or, for non-associative arrays:

或者,对于非关联数组:

<?php $prices[1][0]=1; $prices[1][1]=0.7; $prices[0][0]=1.3; $prices[0][1]=0.5;

What about assigning all the values when we create the array? Since our table has two levels, the first being the city and the second one the item, we declare the array like a series of arrays within another:

创建数组时如何分配所有值呢? 由于我们的表格有两个层次,第一个层次是城市,第二个层次是项目,因此我们将数组声明为类似于另一个数组中的一系列数组:

<?php $prices = array("Los Angeles" => array("hamburger" => 1.3, "fries" => 0.5), "New York" => array("hamburger" => 1, "fries" => 0.7));

You’ll find you often represent the keys with variables when you work with arrays. This is very useful for creating arrays whose values can be mechanically computed. For example, this loop creates an 10-element array with values that are the square of the keys:

您会发现在使用数组时,经常用变量代表键。 这对于创建其值可以机械计算的数组非常有用。 例如,此循环创建一个包含10个元素的数组,其值是键的平方:

<?php $squares = array(); for ($key = 0; $key < 10; $key++) { $squares[$key] = $key * $key; }

The resulting array $squares is populated the same as if we had written:

结果数组$squares的填充方式与我们编写时相同:

<?php $squares = array(); $squares[0] = 0; $squares[1] = 1; $squares[2] = 4; $squares[3] = 9; ... $squares[9] = 81;

使用数组 (Using Arrays)

We’ve learned how to create and fill arrays with values, so how about retrieving these values? To use a value in an array you only have to refer to it with the name of the array variable and the desired index. This way, the price of a hamburger in New York is:

我们已经学习了如何用值创建和填充数组,那么如何检索这些值呢? 要在数组中使用值,只需用数组变量的名称和所需的索引引用它即可。 这样,纽约汉堡的价格为:

<?php $price = $pricesNYC["hamburger"];

or:

要么:

<?php $price = $prices["New York"]["hamburger"];

If we want the cost of a snack (burger+fries) in Los Angeles, we could calculate it as:

如果我们想要洛杉矶的小吃(汉堡+薯条)的价格,可以将其计算为:

<?php $price = $prices["Los Angeles"]["hamburger"] + $prices["Los Angeles"]["fries"];

Suppose we want a list of the cost of snack is all towns. As good programmers we wouldn’t dream of repeating the statement for all cities. Rather, we’d try to write a loop instead. It’s a good idea, but which looping construct should we use? Let’s try a for-loop:

假设我们要列出所有城镇的小吃成本。 作为优秀的程序员,我们不会梦想在所有城市重复该声明。 相反,我们将尝试编写一个循环。 这是一个好主意,但是我们应该使用哪种循环构造? 让我们尝试一个for -loop:

<?php for ($key = _start_; $key <= _end_; $key++) { $price = $prices[$key]["hamburger"] + $prices[$key]["fries"]; }

Hrm… that doesn’t work because the keys to the array are strings! We don’t know what to use for _start_ or _end_. Fortunately, PHP has a foreach-loop that runs through every element of an array, which is exactly what we want to do:

嗯……那行不通,因为数组的键是字符串! 我们不知道_start_或_end_使用什么。 幸运的是,PHP有一个foreach -loop foreach数组的每个元素,这正是我们想要做的:

<?php foreach ($prices as $snack) { $price = $snack["hamburger"] + $snack["fries"]; }

This loop will run through array $prices two times as it has two first-level elements. On the first run, it will extract the array that has the prices for burgers and fries in New York. We call this array $snack. The prices are then added by looking up the values using the keys hamburger and fries. Of course in a real script something else should happen to $price, like being printed or sent to a data table, but we don’t need to do that here. The first-level array is then automatically incremented to the next element and the loop makes the second-level array with prices for Los Angeles available as $snack.

此循环将遍历数组$prices两次,因为它具有两个第一级元素。 第一次运行时,它将提取包含纽约汉堡和薯条价格的数组。 我们将此数组称为$ snack 。 然后通过使用汉堡包和薯条键查找值来添加价格。 当然,在实际脚本中, $price应该发生其他事情,例如被打印或发送到数据表,但是我们不需要在这里这样做。 然后,第一级数组将自动递增到下一个元素,循环使包含洛杉矶价格的第二级数组作为$ snack可用。

It is possible to nest foreach-loops. Just for the sake of one last example, let’s compute the prices using two loops. If this is confusing, copy it down with pen and paper (a centuries old study device that does wonders for enlightenment) and carefully read through it.

可以嵌套foreach -loops。 仅为了最后一个示例,让我们使用两个循环来计算价格。 如果这令人困惑,请用笔和纸(一个世纪的古老学习工具,能启发人的思想)将其抄下来,并仔细阅读。

<?php foreach ($prices as $city => $snack) { echo "<b>" . $city . "</b><br>"; foreach ($snack as $item => $price) { echo $item . " = " . $price . "<br>"; } }

foreach can use the => syntax to make the both the current key and value available to the body of the loop. The output of this loop will send the prices of hamburgers and fries grouped by city to the browser.

foreach可以使用=>语法将当前键和值都提供给循环主体。 此循环的输出会将按城市分组的汉堡包和薯条的价格发送到浏览器。

结论 (Conclusion)

Arrays are a very, very important and versatile data structure. They are handy for grouping all sorts of related information together, and are really easy to use once you get the hang of them. But you can do much more with them than just adding prices. I am fond of using them for customizing scripts, creating key/value pairs for data like website domain name, description, keywords, database login credentials, etc. Also note the PHP super global variables like $_GET, $_POST, $_SESSION and $_SERVER are all arrays. Now that you’re on your way to becoming a proficient array user, you’ll notice them all around you!

数组是非常非常重要且用途广泛的数据结构。 它们非常便于将各种相关信息组合在一起,并且一旦掌握了它们,便非常易于使用。 但是,您可以为他们做更多的事情,而不仅仅是增加价格。 我喜欢用它们来自定义脚本,为网站域名,描述,关键字,数据库登录凭据等数据创建键/值对。还要注意PHP超全局变量,例如$_GET , $_POST , $_SESSION和$_SERVER都是数组。 现在,您正要成为熟练的阵列用户,您会注意到他们周围的一切!

Gee, all those tables and arrays made me hungry. I think I’m going to take the elevator down and have a burger with fries. Or rather do I fancy fish and chips?

哎呀,所有这些桌子和阵列都让我饿了。 我想我要坐电梯下来,去吃汉堡和薯条。 还是我喜欢炸鱼和薯条?

Image via keko64 / Shutterstock

图片来自keko64 / Shutterstock

翻译自: https://www.sitepoint.com/introduction-to-php-arrays/

php 数组添加数组

最新回复(0)