Home  >  Article  >  Backend Development  >  Summary of how to use php arrays

Summary of how to use php arrays

伊谢尔伦
伊谢尔伦Original
2017-06-22 17:59:351510browse

Using arrays
An array is a variable that can store a set or series of values. An array can have many elements. Each element has a value, such as text, a number, or another array. An array that contains other arrays is called a multidimensional array.

What is an array
A scalar variable is a named area used to store values. Likewise, an array is a named area used to store a series of variable values, so you can use arrays to organize scalar variables.
The values ​​stored in the array are called array elements. Each array element has an associated index (also called a key), which can be used to access the element. In most programming languages, arrays have numerical indexes, and these indexes usually start at 0 or 1.

Numeric index array
In PHP, the default value of numeric index starts from 0, but of course it can be changed.
1. Initialization of digital index array
$porducts = array('Tires', 'Oil', 'Spark Plugs');
Just like the echo statement, array() is actually a language structure , rather than a function.
Depending on the different requirements for the contents of the array, there may be no need to manually initialize them like the above example. If the required data is held in another array, you can simply copy the array to another array using the operator "=".
If you need to save the numbers in ascending order in an array, you can use the range() function to automatically create this array. The following line of code will create an array of numbers from 1 to 10: $numbers = range(1,10);
The range() function has an optional third parameter that allows setting values ​​between A step of. For example, if you need to create an array of odd numbers between 1 and 10, you can use the following code: $odds = range(1,10,2);
The range() function can also operate on characters, such as: $letters = range('a', 'z');
2. Access the contents of the array
To access the contents of a variable, you can use its name directly. If the variable is an array, its contents can be accessed using a combination of the variable name and a keyword or index. The keyword or index will specify the variable we want to access. The index is enclosed in square brackets after the variable name.
By default, element 0 is the first element of the array.
Please note that although PHP's string parsing function is very powerful and intelligent, it can cause confusion. When you embed arrays or other variables in double-quoted strings, if they are not interpreted correctly, you can place them outside the double quotes, or look up Chapter 4, "String Operations and Regular Expressions" for more complex syntax. Like other variables in PHP, arrays do not need to be initialized or created in advance. They are automatically created the first time they are used.
3. Use loops to access arrays
Since arrays use ordered numbers as indexes, you can easily display the contents of the array using a for loop.
for ($i=0; $ic6ff941ae3a9f754be3d9bc244d26d5a100, ' Oil'=>10, 'Spark Plugs'=>4 );
The symbol between the keyword and the value is just a greater than sign and an equal sign.
2 Access array elements
Similarly, you can use variable names and keywords to access the contents of the array. For example $prices['Tires'].
3 Using loop statements
Because the index of the relevant array is not a number, it is impossible to use a simple counter to operate on the array in a for loop statement. But you can use foreach loop or list() and each() structures.
The foreach() loop has a different structure when using the foreach loop statement to operate on related arrays. You can use keywords as follows:

The

foreach ($prices as $key => $value)
echo $key.&#39;=>&#39;.$value.&#39;<br />&#39;;
如下所示的代码将使用each()结构打印$prices数组的内容:
while( $element = each($prices))
{
echo $element[&#39;key&#39;];
echo &#39; - &#39;;
echo $element[&#39;value&#39;];
echo &#39;<br />&#39;;
}

each() function will return the current element of the array and the next element as the current element. Because each() function is called in a while loop, it will return each element in the array in order, and when it reaches the end of the array, the loop operation will terminate.
In this code, the variable $element is an array. When each() is called, it returns an array with 4 numeric values ​​and 4 indices pointing to the array positions. Positions key and 0 contain the key of the current element, while positions value and 1 contain the value of the current element. While it makes no difference which method you choose, we have chosen to use named locations rather than numerically indexed locations.
Also, there is a more advanced and common way to accomplish the same operation. The function list() can be used to decompose an array into a series of values. The two values ​​returned by the function each() can be separated as follows: list( $product, $price) = each( $price);
The above code uses each() to remove the current element from the $prices array, and Return it as an array and then point to the next element. It also uses list() to change the two elements 0 and 1 contained in the array returned by each() into two new variables named $product and $price.
We can loop through the entire $prices array and display its contents using a short script like this:

while(list($prodct, $pirce) = each($prices))
echo "$product - $price<br />";

The output of this code is the same as the output of the previous script, but it Easier to read because list() allows naming new variables.
One thing to note is that when using the each() function, the array will record the current element. If you want to use the array twice in the same script, you must use the reset() function to reset the current element to the beginning of the array. To iterate through the prices array again, you can use code like this:
reset($prices);
while(list($product, $price) = each($prices))
echo "$product - $pricedf250b2156c434f3390392d09b1c9563";

Array operator
+Union, ==Equal, ===Identity, !=Not equivalent, a8093152e673feb7aba1828c43532094Not equivalent, !== is not identical.
The union operator attempts to add the elements in $b to the end of $a. If elements in $b have the same index as some elements in $a, they will not be added. That is, the elements in $a will not be overwritten.

Multidimensional array
An array is not necessarily a simple list of keys and values ​​- each position in the array can also hold another array. Using this method, a two-dimensional array can be created. You can think of a two-dimensional array as a matrix, or a network with width and height or rows and columns.

Array sorting
1 Use the sort() function
The sort() function is case-sensitive. All capital letters appear before lowercase letters. So ‘A’ is less than ‘Z’, and ‘Z’ is less than ‘a’.
The second parameter of this function is optional. This optional parameter can be passed SORT_REGULAR (default), SORT_NUMERIC or SORT_STRING. The ability to specify a sort type is useful, for example, when comparing strings that may contain the numbers 2 and 12. From a mathematical point of view, 2 is less than 12, but as a string, '12' is less than '2'.
2 Use the asort() function and ksort() function to sort related arrays
The function asort() sorts based on the value of each element of the array. The ksort() function sorts by keyword rather than by value.
3 Reverse sort
The function rsort() sorts a one-dimensional numeric index array in descending order. The function arsort() sorts a one-dimensional associative array in descending order of the value of each element. The function krsort() sorts the one-dimensional array in descending order according to the keys of the array elements.
To access the data in a one-dimensional array, you need to use the name of the array and the index of the element. Two-dimensional arrays are similar to one-dimensional arrays, except that an element has two indexes - row and column.
You can use a double for loop to achieve the same effect:

for ( $row=0; $row<3; $row++ )
{
for ( $column=0; $column<3; $column++ )
{
echo &#39;|&#39;.$products[$row][$column];
|
echo &#39;|<br />&#39;;
}

If you use this code for a large array, it will be much simpler.
You may prefer to create column names instead of numbers. You can use code like this:

$products = array ( array ( &#39;Code&#39;=>&#39;TIR&#39;, &#39;Descrīption&#39;=>&#39;Tires&#39;, &#39;Price&#39;=>100 ), array ( &#39;Code&#39;=>&#39;OIL&#39;, &#39;Descrīption&#39;=>&#39;Oil&#39;, &#39;Price&#39;=>10 ), array ( &#39;Code&#39;=>&#39;SPK&#39;, &#39;Descrīption&#39;=>&#39;Spark Plugs&#39;, &#39;Price&#39;=>4 ) };

If you wish to retrieve a single value, it will be much easier to use this array. Remember, it is easier to remember what you describe by saving it in a column named after it than by saving it in the so-called first column. With descriptive indexing, there is no need to remember that an element is stored at [x][y] position. Using a meaningful pair of row and column names as an index makes it easy to find the data you need.
Then, we cannot use a simple for loop to traverse each column in order. You can use a for loop to iterate over the outer numerically indexed array $products. Each row of the $products array is an array with a descriptive index. Using each() and list() functions in a while loop, you can traverse the entire internal array. Therefore, a for loop with a while loop embedded inside is required.

for ( $row = 0; $row < 3; $row++ }
{
while ( list ( $key, $value ) = each ( $products[$row] ) )
{
echo "|$value";
}
echo &#39;|<br />&#39;;
}

三维数组具有高、宽、深的概念。如果能轻松地将一个二维数组想像成一个有行和列的表格,那么就可以将三维数组想像成一堆像这样的表格。每个元素可以通过层、行和列进行引用。
根据创建多维数组的方法,可以创建四维、五维或六维数组。在PHP中,并没有设置数组维数的限制,但人们很难设想一个多于三维的数组。大多数的实际问题在逻辑上只需要使用三维或者更少维的数组结构就可以了。

多维数组的排序
对 多于一维的数组进行排序,或者不按字母和数字的顺序进行排,要复杂得多。PHP知道如何比较两个数字或字符串,但在多维数组中,每个元素都是一个数组。 PHP不知道如何比较两个数组,所以需要建立一个比较它们的方法。在大多数情况下,单词和数字的顺序是显而易见的——但对于复杂的对象,问题就会多一些。
1 用户定义排序
usort()中的“u”代表“user”,因为这个函数要求传入用户定义的比较函数。asort和ksort对应的版本uasort()和uksort()也要求传入用户定义的比较函数。
类似于asort(),当对非数字索引数组的值进行排序时,uasort()才会被使用。如果值是简单的数字或文本则可以使用asort。如果要比较的值像数组一样复杂,可以定义一个比较函数,然后使用uasort()。
类似于ksort(),当对非数字索引数组的关键字进行排序时才使用uksort()。如果值是简单的数字或文本就使用ksort。如果要比较的对象像数组一样复杂,可以定义一个比较函数,然后使用uksort()。
2 反向用户排序
函数sort()、asort()和ksort()都分别对应一个带字母“r”的反向排序函数。用户定义的排序没有反向变体,但可以对一个多维数组进行反向排序。

对数组进行重新排序
1 使用shuffle()函数
在PHP的早期版本中,shuffle()要求调用srand()函数时首先提供一个随机数生成器。如今,这个步骤已经不再需要了。
如果这个函数对你非常重要,可以在程序中应用该函数之前在服务器上测试它。
由于并不需要真正重新排序整个数组,使用array_rand()函数可以实现相同的功能。
2 使用array_reverse()函数
array_reverse()函数使用一个数组作参数,返回一个内容与参数数组相同但顺序相反的数组。
因为单独使用range()函数将创建一个升序序列,所以必须使用sort()函数或array_reverse()函数将数组中的数字变为降序。或者,也可以使用for循环通过一次一个元素的方式创建这个数组。如:

$numbers = array();
for ($i=10; $i>0; $i--)
array_push( $numbers, $i );

一个for循环可以像这样按降序方式运行。可以将计数器
一个for循环可以像这样按降序方式运行。可以将计数器的初始值设为一个大数,在每次循环末尾使用运算符“--”将计数器减1。
在这里,我们创建了一个空数组,然后使用array_push()函数将每个新元素添加到数组的末尾。请注意,和array_push()相反的函数是array_pop(),这个函数用来删除并返回数组末尾的一个元素。
或者,也可以使用array_reverse()函数将由range()函数所创建的数组进行反向排序。
请注意,array_reverse()函数将返回一个原数组修改后的副本。如果不再需要原来的数组,比如在这个例子中,可以用新的副本覆盖原来的版本。
如果数据只是一系列的整数,可以通过将-1作为range()函数的第三个可选调参数,以相反的顺序创建该数组。

从文件载入数组
使用file()函数将整个文件载入一个数组中。文件中的每行则成为数组中的一个元素。使用了count()函数来统计数组中的元素个数。
explode("\t", $orders[$i])
explode()函数可以将传入的字符串分割成一个个小块。每个制表符成为两个元素之间的断点。这个函数的可选参数limit可以用来限制被返回的最大块数。
可以使用许多方法从字符串中提取数字。在这里,我们使用了intval()函数。它可以将一个字符串转化成一个整数。这个转换是相当智能化的,它可以忽略某些部分,例如标签就不能转换成数字。

执行其他的数组操作
1 在数组中浏览:each()、current()、reset()、end()、next()、pos()和prev()
前面已经提到,每个数组都有一个内部指针指向数组中的当前元素。当使用函数each()时,就间接地使用了这个指针,但是也可以直接使用和操作这个指针。
如果创建一个新数组,那么当前指针就将被初始化,并指向数组的第一个元素。
调用next()或each()将使指针前移一个元素。调用each($array_name)会在指针前移一个位置之前返回当前元素。next()函数则有些不同——调用next($array_name)是将指针前移,然后再返回新的当前元素。
调用end($array_name)可以将指针移到数组末尾。
要反向遍历一个数组,可以使用end()和prev()函数。prev()函数和next()函数相反。它是将当前指针往回移一个位置然后再返回新的当前元素。
2 对数组的每一个元素应用任何函数:array_walk()
array_walk()函数需要三个参数。第一个是arr,也就是需要处理的数组。第二个是func,也就是用户自定义并将作用于数组中每个元素的函数。第三个参数userdata是可选的,如果使用它,它可以作为一个参数传递给我们自己的函数。
看一个销微复杂点的例子:

function my_multiply(&$value, $key, $factor)
{
$value *= $factor;
}
array_walk(&$array, &#39;my_multiply&#39;, 3);

在这里,我们定义了一个名为my_multiply()的函数,它可以用所提供的乘法因子去乘以数组中的每个元素。
此外,还有一个需要注意的问题是传递毵数$value的方式。在my_multiply()的函数定义中,变量前面的地址符(&)意味着$value是按引用方式传递的。按引用方式传递允许函数修改数组的内容。
3 统计数组元素个数:count()、sizeof()和array_count_values()
count()函数和sizeof()函数具有同样的用途,都可以返回数组元素的个数。可以得到一个常规标量变量中的元素个数,如果传递给这个函数的数组是一个空数组,或者是一个没有经过设定的变量,返回的数组个数就是0。
如 果调用array_count_values($array),这个函数将会统计每个特定的值在数组$array中出现过的次数(这就是数组的基数集)。 这个函数将返回一个包含频率表的相关数组。这个数组包含数组$array中的所有值,并以这些值作为相关数组的关键字。每个关键字所对应的数值就是关键字 在数组$array中出现的次数。
4 将数组转换成标量变量:extract()
对于一个非数字索引数组,而该数组又有许多关键字-值对,可以使用函数extract()将它们转换成一系列的标量变量。
函数extract()的作用是通过一个数组创建一系列的标量变量,这些变量的名称必须是数组中关键字的名称,而变量值则是数组中的值。
extract()函数具有两个可选参数:extract_type和prefix。变量extract_type将告诉extract()函数如何处理冲突。有时可能已经存在一个和数组关键字同名的变量,该函数的默认操作是覆盖已有的变量。
两个最常用的选项是EXTR_OVERWRITE(默认值)和EXTR_PREFIX_ALL。当知道会发生特定的冲突并且希望跳过该关键字或要给它加上前缀时,可能会用到其他选项。
extract()可以提取出一个元素,该元素的关键字必须是一个有效的变量名称,这就意味着以数字开始或包含空格的关键字将被跳过。

The above is the detailed content of Summary of how to use php arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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