Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
PHP Programming With MySQL Second Edition.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
43.07 Mб
Скачать

Manipulating Arrays

In comparison, the following code declares and initializes

$ProvincialCapitals[] and $TerritorialCapitals[] as associa-

tive arrays. The $TerritorialCapitals[] array is appended to the

$ProvincialCapitals[] array with the addition (+) operator, and the

resulting array is assigned to an array named $CanadianCapitals[].

Because the keys in the $TerritorialCapitals[] array do not

exist in the $ProvincialCapitals[] array, the elements in the

$TerritorialCapitals[] array are successfully appended to the ele-

ments in the $ProvincialCapitals[] array, as shown in Figure 6-17.

$ProvincialCapitals = array(

"Newfoundland and Labrador" => "St. John's",

"Prince Edward Island" => "Charlottetown",

"Nova Scotia" => "Halifax",

"New Brunswick" => "Fredericton",

"Quebec" => "Quebec City",

"Ontario" => "Toronto",

"Manitoba" => "Winnipeg",

"Saskatchewan" => "Regina",

"Alberta"=>"Edmonton",

"British Columbia" => "Victoria");

$TerritorialCapitals = array(

"Nunavut" => "Iqaluit",

"Northwest Territories" => "Yellowknife",

"Yukon Territory" => "Whitehorse");

$CanadianCapitals = $ProvincialCapitals +

$TerritorialCapitals;

echo "<pre>\n";

print_r($CanadianCapitals);

echo "</pre>\n";

345

Figure 6-17

Output of two associative arrays combined with the addition operator


CHAPTER 6

Manipulating Arrays

You can also combine two arrays with the compound assignment

operator (+=), as follows:

$CanadianCapitals += $ProvincialCapitals;

$CanadianCapitals += $TerritorialCapitals;

346

Instead of appending one array to another, you can merge two or more

arrays with the array_merge() function. The syntax for the function is

$new_array = array_merge(array1, array2 [, array3, ...]);.

The array1 array is copied to the $new_array array, then the array2

array is appended to $new_array, then the array3 array is appended

to $new_array, and so on. If you use the array_merge() func-

tion with associative arrays, the keys in the array you are append-

ing overwrite any duplicate keys from previously merged arrays.

With indexed arrays, all elements in one array are appended to

another array and renumbered. The following statement demon-

strates how to combine the associative $ProvincialCapitals[] and

$TerritorialCapitals[] arrays:

$CanadianCapitals = array_merge(

$ProvincialCapitals,

$TerritorialCapitals);

The following code demonstrates how to combine the indexed

$Provinces[] and $Territories[] arrays. In contrast to the

examples that used the addition (+) and additive compound assign-

ment (+=) operators, this version successfully combines both arrays,

renumbers the indexes, and stores the result in the $Canada[] array,

as shown in Figure 6-18.

$Provinces = array("Newfoundland and Labrador",

"Prince Edward Island", "Nova Scotia",

"New Brunswick", "Quebec", "Ontario",

"Manitoba", "Saskatchewan", "Alberta",

"British Columbia");

$Territories = array("Nunavut",

"Northwest Territories", "Yukon Territory");

$Canada = array_merge($Provinces, $Territories);

echo "<pre>\n";

print_r($Canada);

echo "</pre>\n";


Manipulating Arrays

347

Output of two indexed arrays combined with the

array_merge() function

Figure 6-18

In addition to appending and merging the elements in two arrays,

you can create a new associative array that uses the values from one

array as keys and element values from another array. To do this, you

use the array_combine() function. For example, the following code

declares a $Territories[] array and a TerritorialCapitals[]

array and then combines the two arrays into a new array named

$CanadianTerritories[].

$Territories = array("Nunavut",

"Northwest Territories",

"Yukon Territory");

$TerritorialCapitals = array("Iqaluit",

"Yellowknife", "Whitehorse");

$CanadianTerritories = array_combine(

$Territories, $TerritorialCapitals);

To add the array_combine() function to the MessageBoard.php file

to create a new associative array:

1.

2.

Return to the MessageBoard.php file in your text editor.

Modify the for loop in the else clause as follows. The sec-

ond and third statements in the loop create two separate

arrays: $KeyArray[] and $ValueArray[]. The third state-

ment then uses the array_combine() function to create

$KeyMessageArray[].


CHAPTER 6

Manipulating Arrays

for ($i = 0; $i < $count; ++$i) {

$CurrMsg = explode("~", $MessageArray[$i]);

$KeyArray[] = $CurrMsg[0];

$ValueArray[] = $CurrMsg[1]. "~" .

$CurrMsg[2];

$KeyMessageArray = array_combine($KeyArray,

$ValueArray);

}

348

3.

4.

Save the MessageBoard.php file.

Open the MessageBoard.php file in your Web browser by

entering the following URL: http://<yourserver>/PHP_

Projects/Chapter.06/Chapter/MessageBoard.php. The mes-

sage list should look the same as it did before you added the

array_combine() function.

Close your Web browser window.

5.

Comparing Arrays

PHP includes several functions for comparing the con-

tents of two or more arrays. Two of the most basic com-

parison functions are array_diff() and array_intersect().

The array_diff() function returns an array of elements

that exist in one array but not in any other arrays to which

it is compared. The syntax for the array_diff() function is

$new_array = array_diff(array1, array2 [, array3, ...]);.

A new array is returned containing elements that exist in $array1

but do not exist in any of the other array arguments. Keys and

indexes are not renumbered in the new array. As an example, con-

sider the following code, which declares and initializes an array

named $Top10inArea[] that contains the names of the 10 largest

countries in area, and another array named $Top10inPopulation[]

that contains the names of the 10 largest countries in population.

The array_diff() function determines which of the most populous

countries are not the largest countries by comparing the values in the

$Top10inPopulation[] and $Top10inArea[] arrays, and assigns the

difference to the $Result[] array. The array_values() statement

then renumbers the indexes in the $Result[] array. The $Result[]

array contains the five countries shown in Figure 6-19; these coun-

tries are among the largest in population, but not in area.

$Top10inArea = array("Russia", "China",

"Canada", "United States", "Brazil",

"Australia", "India", "Argentina",

"Kazakhstan", "Algeria");

$Top10inPopulation = array("China", "India",

"United States", "Indonesia", "Brazil",

"Pakistan", "Bangladesh", "Russia",

"Nigeria", "Japan");


Manipulating Arrays

$Result = array_diff($Top10inPopulation,

$Top10inArea);

$Result = array_values($Result);

echo "<p>The following of the most populous

countries are not also the largest in

area:</p>\n";

echo "<p>\n";

for ($i = 0; $i < count($Result); ++$i) {

echo "{$Result[$i]}<br />\n";

}

echo "</p>\n";

349

Figure 6-19

Output of an array created with the array_diff() function

The array_intersect() function returns an array of the

elements that are common to all of the arrays that are

compared. The syntax for the array_intersect() function is

new_array = array_intersect(array1, array2 [, array3, ...]);.

As with the array_diff() function, keys and indexes are not renum-

bered in the new array, so you must use the array_values() func-

tion to renumber an indexed array. The following code uses the

array_intersect() function on the same $Top10inArea[] and

$Top10inPopulation[] arrays. The output in Figure 6-20 shows the

names of the five countries that are among the largest in both area

and population.

$Result = array_intersect($Top10inPopulation,

$Top10inArea);

$Result = array_values($Result);

echo "<p>The following of the most populous

countries are also among the largest in

area:</p>\n";

echo "<p>\n";

for ($i = 0; $i < count($Result); ++$i) {

echo "{$Result[$i]}<br />\n";

}

echo "</p>\n";


CHAPTER 6

Manipulating Arrays

350

Figure 6-20

function

Output of an array created with the array_intersect()

Short Quiz

1.

Explain the difference between the sort() and asort()

functions.

What is the purpose of the ksort() and krsort() functions?

What are the two methods of combining arrays?

Explain the difference between the array_diff() and

array_intersect() functions.

2.

3.

4.

Understanding Multidimensional Arrays

The arrays you have created so far are known as one-dimensional

arrays because they consist of a single index or key. You can also

create multidimensional arrays that consist of multiple indexes

or keys. The procedures for creating multidimensional arrays are

essentially the same as for indexed and associative arrays. However,

to avoid confusion, you will first learn how to create indexed multi-

dimensional arrays.

Understanding Multidimensional Arrays

Creating Two-Dimensional Indexed Arrays

The most common type of multidimensional array is a two-

dimensional array, which has two sets of indexes or keys. To under-

stand how a two-dimensional array works, first consider the following

one-dimensional indexed array named $Gallons[] that converts gal-

lons to various other measures of volume:

$Gallons = array(

128, // ounces

16, // cups

8, // pints

4 // quarts

);

351

This single-dimensional array works fine if you only need to store a

single set of volume conversions. However, what if you want to store

additional volume conversions, such as quarts to cups? Table 6-3 lists

conversion rates for each of the measures of volume in the preceding

example.

Ounces

Ounces

Cups

Pints

Quarts

Gallons

Table 6-3

1

8

16

32

128

Cups

0.125

1

2

4

16

Pints

0.0625

0.5

1

2

8

Quarts

0.03125

0.25

0.5

1

4

Gallons

0.0078125

0.0625

0.125

0.25

1

Volume conversion table

The first set of indexes (or keys) in a two-dimensional array deter-

mines the number of rows in the array, and the second set of indexes

(or keys) determines the number of columns. The easiest way to

create a two-dimensional array is to first create individual arrays for

each of the rows the array will include. The following statements

declare and initialize individual indexed arrays for each of the rows in

Table 6-3:

$Ounces = array(1, 0.125, 0.0625, 0.03125,

0.0078125);

$Cups = array(8, 1, 0.5, 0.25, 0.0625);

$Pints = array(16, 2, 1, 0.5, 0.125);

$Quarts = array(32, 4, 2, 1, 0.25);

$Gallons = array(128, 16, 8, 4, 1);

A multidimensional array in PHP is essentially “an array of arrays.”

To declare and initialize a multidimensional array with the preced-

ing data, you include each of the array names as an element value in


CHAPTER 6

Manipulating Arrays

a new declaration. For example, the following statement uses each of

the preceding array names to declare and initialize a two-dimensional

indexed array named $VolumeConversions[]:

$VolumeConversions = array($Ounces, $Cups,

$Pints, $Quarts, $Gallons);

352

You refer to the values in a multidimensional indexed array by

including two sets of brackets following the array name with

the syntax array_name[index][index]. The first set of brackets

refers to the row, and the second set of brackets refers to the col-

umn. Table 6-4 illustrates the elements and index numbers in the

$VolumeConversions array.

0 (Ounces) 1 (Cups)

0 (Ounces)

1 (Cups)

2 (Pints)

3 (Quarts)

4 (Gallons)

Table 6-4

1

8

16

32

128

0.125

1

2

4

16

2 (Pints)

0.0625

0.5

1

2

8

3 (Quarts)

0.03125

0.25

0.5

1

4

4 (Gallons)

0.0078125

0.0625

0.125

0.25

1

Elements and indexes in the $VolumeConversions[] array

To access the conversion value from quarts to cups, you

refer to the fourth row (index 3) and second column

(index 1) of the $VolumeConversions[] array as follows:

$VolumeConversions[3][1]. The following statement displays the

conversion value from quarts to cups:

echo "<p>1 quart converts to " .

$VolumeConversions[3][1] . " cups.</p>\n";

Use the same format to set or modify an element value in a two-

dimensional indexed array. The following statement demonstrates

how to set the conversion value for cups (row index 1) to quarts (col-

umn index 3):

$ConversionValues[1][3] = 0.25;

To add an indexed two-dimensional array to the MessageBoard.php

file for displaying the contents of the messages.txt file:

1.

2.

Return to the MessageBoard.php file in your text editor.

Replace the first for loop in the else clause with the fol-

lowing foreach loop. This construct loops through

$MessageArray[] and explodes each element into the

$CurrMsg[] array. Notice that the last statement in the

loop assigns the $CurrMsg[] array to $KeyMessageArray[],


Understanding Multidimensional Arrays

which creates a two-dimensional array. Because the

$KeyMessageArray[] statement includes two array brack-

ets at the end of the array name, each subsequent value in

$CurrMsg[] is appended to $KeyMessageArray[].

foreach ($MessageArray as $Message) {

$CurrMsg = explode("~", $Message);

$KeyMessageArray[] = $CurrMsg;

}

353

3.

Delete the following statement:

$Index = 1;

4.

Modify the second foreach loop at the end of the else

clause into the following for loop. The $i variable is used for

looping through the elements in the first dimension of the

array. However, because each “row” in the two-dimensional

$KeyMessageArray[] only contains three elements (subject,

name, and message), the second dimension is referred to

using literal values.

for ($i = 0; $i < $count; ++$i) {

echo "<tr>\n";

echo "<td width=\"5%\"

style=\"text-align:center\"><span

style=\"font-weight:bold\">" .

($i + 1) . "</span></td>\n";

echo "<td width=\"85%\"><span

style=\"font-weight:bold\">

Subject:</span> " .

htmlentities(

$KeyMessageArray[$i][0]) .

"<br />";

echo "<span style=\"font-weight:bold\">

Name:</span> " . htmlentities(

$KeyMessageArray[$i][1]) .

"<br />";

echo "<span style=\"font-weight:bold;

text-decoration:underline\">

Message</span><br />" .

htmlentities(

$KeyMessageArray[$i][2]) .

"</td>\n";

echo "<td width=\"10%\"

style=\"text-align:center\"><a

href='MessageBoard.php?" .

"action=Delete%20Message&" .

"message=$i'>Delete This

Message</a></td>\n";

echo "</tr>\n";

}


Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]