Học làm web (x8) - PHP: sorting arrays

Bài trước: Học làm web (x7) - PHP: using arrays
-----

Array operatiors (p81)


Operator

Name

Example

Result

+

Union

$a + $b

Union of $a and $b. The array $b is appended to $a, but any key clashed are not added.

=

Equality

$a == $b

True if $a and $b contain the same elements.

===

Identity

$a === $b

True if $a and $b contain the same elements, with the same types, in the same order.

!=

inequality

$a != $b

True if $a and $b do not contain the same elements.

<> 

inequality

$a <> $b

Same as !=

!==

Non-identity

$a !== $b

True if $a and $b do not contain the same elements, with the same types, in the same order.


Multidimensional arrays (p82)


You can think of a two-dimentional array as a matrix, or grid, with width and height or rows and columns.

If you want to store more than one piece of data about each of Bob’s products, you could use a two-dimentional array. Table below shows Bob’s products represented as a two-dimentional array with each row representing an individual product and each column representing a stored product attribute.

product >
Code
Description
Price
TIR
Tires
100
OIL
Oil
10
SPK
Spark Plugs
4
Product attribute >

Using PHP, you would write the following code to set up the data in the array shown in above table:

$products = array( array(‘TIR’, ‘Tires’, 100),
                        array(‘OIL’, ‘Oil’, 10),
                        array(‘SPK’, ‘Spark Plugs’, 4));

You can see from this definition that the $products array now contains three arrays.

To access the data in a two-dimentional array you need the name of the array and two indices: a row and a column.

To display the contents of this array, you could manually access each element in order like this:

echo '|'.$products[0][0].'|'.$products[0][1].'|'.$products[0][2].'|<br>';
echo '|'.$products[1][0].'|'.$products[1][1].'|'.$products[1][2].'|<br>';
echo '|'.$products[2][0].'|'.$products[2][1].'|'.$products[2][2].'|<br>';

Alternatively, you could place a for loop inside another for loop to achieve the same result:

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

Both versions of this code produce the same output in the browser:

|TIR|Tires|100||OIL|Oil|10|
|SPK|Spark Plugs|4|

You might prefer to create column names instead of numbers, you would use the following code:

$products = array(array('Code' => 'TIR',
'Description' => 'Tires',
'Price' => 100
),
array('Code' => 'OIL',
'Description' => 'Oil',
'Price' => 10
),
array('Code' => 'SPK',
'Description' => 'Spark Plugs',
'Price' =>4
)
);

This array is easier to work with if you want to retrieve a single value. Remembering that the description is stored in the Description column is easier than remembering it is stored in column 1. Using descriptive indices, you do not need to remember that an item is stored at [x][y]. You can easily find your data by referring to a location with meaningful row and column names.

You do, however, lose the ability to use a simple for loop to step through each column in turn. Here is one way to write code to display this array:

for ($row = 0; $row < 3; $row++){
echo '|'.$products[$row]['Code'].'|'.$products[$row]['Description'].
'|'.$products[$row]['Price'].'|<br />';
}

Using a for loop, you can step through the outer, numerically indexed $products array. Each row in the $products array is an array with descriptive indices. Using the each() and list() functions in a while loop, you can step through these inner arrays. Therefore, you can use a while loop inside a for loop:

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

Three dimentional arrays (p84)


Sorting Arrays (p85)


Sorting related data stored in an array is often useful. You can easily take a one-dimentional array and sort it into order.

Using sort()

The following code showing the sort() function results in the array being sorted into ascending alphabetical order:

$products = array('Tires', 'Oil', 'Spark Plugs');
sort($products);

You can sort values by numerical order too.

$prices = array(100, 10, 4);
sort($prices);

Note that the sort() function is case sensitive. All capital letters come before all lowercase letters. So A is less than Z, but Z is less than a.

The function also has an optional second parameter. You may pass one of the constants SORT_REGULAR (the default), SORT_NUMERIC, SORT_STRING, SORT_LOCALE_STRING, SORT_NATURAL, SORT_FLAG_CASE.

The ability to specify the sort type is useful when you are comparing strings that might contain numbers, for example, 2 and 12. Numerically, 2 is less than 12, but as strings ‘12’ is less than ‘2’.

Using asort() and ksort to sort arrays (p86)

If you are using an array with descriptive keys to store items and their prices, you need to use different kinds of sort functions to keep keys and values together as they are sorted.

The following code creates an array containing the three products and their associated prices and then sorts the array into ascending price order:

$prices = array('Tires'=>100, 'Oil'=>10, 'Spark Plugs'=>4);
asort($prices);

The function asort() orders the array according to the value of each element. In the array, the values are the prices, and the keys are the textual descriptions. If, instead of sorting by price, you want to sort by description, you can use ksort(), which sorts by key rather than value.

The following code results in the keys of the array being ordered alphabetically: Oil, Spark Plugs, Tires:

$prices = array('Tires'=>100, 'Oil'=>10, 'Spark Plugs'=>4);
ksort($prices);

Sorting in Reverse (p87)

The three different sorting functions––sort(), asort(), and ksort()––sort an array into ascending order. Each function has a matching reverse sort function to sort an array into descending order. The reverse versions are called rsort(), arsort(), and krsort().


Sorting multidimensional arrays (p87)


Sorting arrays with more than one dimension, or by something other than alphabetical or numerical order, is more complicated. PHP knows how to compare two numbers or two text strings, but in a multidimensional array, each element is an array.

There are two approaches to sorting multidimensional arrays: creating a user-defined sort or using the array_multisort() function.

Using the array_multisort() function

The array_multisort() function can be used either to sort multidimensional arrays, or to sort multiple arrays at once.

The following is the definition of a two-dimensional array used earlier. This array stores Bob’s three products with a code, a description, and a price for each:

$products = array(array('TIR', 'Tires', 100),
array('OIL', 'Oil', 10),
array('SPK', 'Spark Plugs', 4));

If we simply take the function array_multisort() and apply it as follows, it will sort the array. But in what order?

array_multisort($products);

As it turns out, this will sort our $products array by the first item in each array, using a regular ascending sort, as follows:

'OIL', 'Oil', 10
'SPK', 'Spark Plugs', 4
'TIR', 'Tires', 100

This function has the following prototype:

bool array_multisort(array &a [, mixed order = SORT_ASC [, mixed sorttype =
SORT_REGULAR [, mixed $... ]]] )

For the ordering you can pass SORT_ASC or SORT_DESC for ascending or descending order, respectively.

For the sort type, array_multisort() supports the same constants as the sort() function.

One important point to note for array_multisort() is that, while it will maintain key-value association when the keys are strings, it will not do so if the keys are numeric, as in this example.

User-defined sorts (p88)

Reverse user sorts (p89)


Reordering arrays (p90)


For some applications, you might want to manipulate the order of the array in other ways than a sort. The function shuffle() randomly reorders the elements of your array. The function array_reverse() gives you a copy of your array with all the elements in reverse order.

Using shuffle()

Bob wants to feature a small number of his products on the front page of his site. He has a large number of products but would like three randomly selected items shown on the front page. So that repeat visitors do not get bored, he would like the three chosen products to be different for each visit. He can easily accomplish his goal if all his products are in an array. Solution is shuffling the array into a random order and then displaying the first three.

Lab 12. Using PHP to produce a dynamic front page for Bob’s auto parts.

<?php
$pictures = array('brakes.png', 'headlight.png',
'spark_plug.png', 'steering_wheel.png',
'tire.png', 'wiper_blade.png');
shuffle($pictures);
?>
<!DOCTYPE html>
<html>
<head>
<title>Bob's Auto Parts</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>
<div align="center">
<table style="width: 100%; border: 0">
<tr>
<?php
for ($i = 0; $i < 3; $i++) {
echo "<td style=\"width: 33%; text-align: center\">
<img src=\"";
echo $pictures[$i];
echo "\"/></td>";
}
?>
</tr>
</table>
</div>
</body>
</html>


Reversing an array (p92)

</////08
-----------
Cập nhật [21/5/2019]
-----------
Xem thêm: Tổng hợp các bài viết về  Học làm web
Xem thêm: Học làm web (x9) - PHP: