Tải bản đầy đủ (.pdf) (609 trang)

Peachpit press PHP 5 advanced

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (10.79 MB, 609 trang )

VISUAL QUICKPRO GUIDE
PHP 5 A
DVANCED
Larry Ullman
Peachpit Press
Visual QuickPro Guide
PHP 5 Advanced
Larry Ullman
Peachpit Press
1249 Eighth Street
Berkeley, CA 94710
510/524-2178
510/524-2221 (fax)
Find us on the Web at: www.peachpit.com
To report errors, please send a note to:
Peachpit Press is a division of Pearson Education.
Copyright © 2007 by Larry Ullman
Editor: Rebecca Gulick
Copy Editor: Robert Campbell
Technical Reviewer: Jay Blanchard
Proofreader: Liz Welch
Production Coordinator: Becky Winter
Compositor: Kate Kaminski
Indexer: Karin Arrigoni
Cover Design: Peachpit Press
Notice of Rights
All rights reserved. No part of this book may be reproduced or transmitted in any form by any
means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written
permission of the publisher. For information on getting permission for reprints and excerpts,
contact


Notice of Liability
The information in this book is distributed on an “As Is” basis, without warranty. While every
precaution has been taken in the preparation of the book, neither the author nor Peachpit Press
shall have any liability to any person or entity with respect to any loss or damage caused or
alleged to be caused directly or indirectly by the instructions contained in this book or by the
computer software and hardware products described in it.
Trademarks
Visual QuickPro Guide is a registered trademark of Peachpit Press, a division of Pearson
Education.
MySQL is a registered trademark of MySQL AB in the United States and in other countries.
Macintosh and Mac OS X are registered trademarks of Apple Inc. Microsoft, Windows, Windows
XP, and Windows Vista are registered trademarks of Microsoft Corp. Screenshots of Web sites in
this book are copyrighted by the original holders.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in this book, and Peachpit was aware
of a trademark claim, the designations appear as requested by the owner of the trademark. All
other product names and services identified throughout this book are used in editorial fashion
only and for the benefit of such companies with no intention of infringement of the trademark.
No such use, or the use of any trade name, is intended to convey endorsement or other affilia-
tion with this book.
ISBN-13: 978-0-321-37601-5 ISBN-10: 0-321-37601-3
9 8 7 6 5 4 3 2 1
Printed and bound in the United States of America
Dedication
To my good friend Michael K. and his family:
I cannot thank you all enough for your con-
tinuing friendship, generosity, and kindness
over these many years.
My utmost thanks to…
Jessica, the love of my life, for just about

everything.
Zoe and Sam, for making my world a
better place.
The grandparents, who traveled far and
often, pitching in with babysitting and
housework so that I might write this book.
Everyone at Peachpit Press for their support,
for their dedication to putting out quality
books, and for everything else they do to
make all this happen.
The most excellent editor, Rebecca Gulick,
for so many reasons.
Bob Campbell, for his spot-on copy editing
and attention to detail.
The production coordinator, Becky Winter,
the compositor, Kate Kaminski, the proof-
reader, Liz Welch, and the indexer, Karin
Arrigoni, who turn my mess of files into an
actual book.
Jay Blanchard, for his technical review.
The readers, the readers, the readers!
Introduction ix
Chapter 1: Advanced PHP Techniques 1
Chapter 2: Developing Web Applications 43
Chapter 3: Advanced Database Concepts 81
Chapter 4: Security Techniques 123
Chapter 5: E-commerce Techniques 169
Chapter 6: Basic Object-Oriented
Programming 233
Chapter 7: Advanced OOP 263

Chapter 8: Real-World OOP 309
Chapter 9: Networking with PHP 347
Chapter 10: PHP and the Server 373
Chapter 11: PHP’s Command-Line Interface 417
Chapter 12: Using PEAR 443
Chapter 13: Ajax 481
Chapter 14: XML and PHP 529
Index 569
v
Contents at a Glance
Contents at a Glance
vi
Table of Contents
Introduction ix
Chapter 1: Advanced PHP Techniques 1
Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . 2
Advanced Function Definitions . . . . . . . . . . . . . . . 18
The Heredoc Syntax . . . . . . . . . . . . . . . . . . . . . . . . . 31
Using printf() and sprintf() . . . . . . . . . . . . . . . . . . . 37
Chapter 2: Developing Web Applications 43
Documenting Code . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Code Style and Structure . . . . . . . . . . . . . . . . . . . . . 47
Modularizing a Web Site . . . . . . . . . . . . . . . . . . . . . 49
Affecting the Browser Cache . . . . . . . . . . . . . . . . . . 74
Chapter 3: Advanced Database Concepts 81
Storing Sessions in a Database . . . . . . . . . . . . . . . . 82
Working with U.S. Zip Codes . . . . . . . . . . . . . . . . . 96
Creating Stored Functions . . . . . . . . . . . . . . . . . . . 110
Displaying Results Horizontally . . . . . . . . . . . . . . 116
Chapter 4: Security Techniques 123

Remembering the Basics . . . . . . . . . . . . . . . . . . . . 124
Validating Form Data . . . . . . . . . . . . . . . . . . . . . . . 126
Using PECL Filter . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Authentication with PEAR Auth . . . . . . . . . . . . . 143
Using MCrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Chapter 5: E-commerce Techniques 169
E-commerce Concepts . . . . . . . . . . . . . . . . . . . . . . 170
Creating the Database . . . . . . . . . . . . . . . . . . . . . . 171
Creating the Configuration File . . . . . . . . . . . . . . 183
Making the Template . . . . . . . . . . . . . . . . . . . . . . . 190
Creating the Index Page . . . . . . . . . . . . . . . . . . . . . 197
Table of Contents
Browsing by Category . . . . . . . . . . . . . . . . . . . . . . . 199
Showing a Product . . . . . . . . . . . . . . . . . . . . . . . . . 205
Implementing a Shopping Cart . . . . . . . . . . . . . . 212
Validating Credit Cards . . . . . . . . . . . . . . . . . . . . . 224
Chapter 6: Basic Object-Oriented
Programming 233
OOP Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Defining a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Creating an Object . . . . . . . . . . . . . . . . . . . . . . . . . 240
The $this Attribute . . . . . . . . . . . . . . . . . . . . . . . . . 244
Creating Constructors . . . . . . . . . . . . . . . . . . . . . . 251
Creating Destructors . . . . . . . . . . . . . . . . . . . . . . . 256
Autoloading Classes . . . . . . . . . . . . . . . . . . . . . . . . 260
Chapter 7: Advanced OOP 263
Advanced Theories . . . . . . . . . . . . . . . . . . . . . . . . . 264
Inheriting Classes . . . . . . . . . . . . . . . . . . . . . . . . . . 266
Inheriting Constructors and Destructors . . . . . 271
Overriding Methods . . . . . . . . . . . . . . . . . . . . . . . . 276

Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Using the Scope Resolution Operator . . . . . . . . . 289
Creating Static Members . . . . . . . . . . . . . . . . . . . . 294
Abstract Classes and Methods . . . . . . . . . . . . . . . 300
Chapter 8: Real-World OOP 309
Catching Exceptions . . . . . . . . . . . . . . . . . . . . . . . . 310
Extending the Exception Class . . . . . . . . . . . . . . 317
Creating a Shopping Cart Class . . . . . . . . . . . . . . 328
Using the Cart Class . . . . . . . . . . . . . . . . . . . . . . . . 340
Chapter 9: Networking with PHP 347
Accessing Other Web Sites . . . . . . . . . . . . . . . . . . 348
Working with Sockets . . . . . . . . . . . . . . . . . . . . . . 355
Performing IP Geolocation . . . . . . . . . . . . . . . . . . 363
Using cURL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Chapter 10: PHP and the Server 373
Compressing Files . . . . . . . . . . . . . . . . . . . . . . . . . . 374
PHP-GTK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
Establishing a cron . . . . . . . . . . . . . . . . . . . . . . . . . 399
Scheduling Tasks on Windows . . . . . . . . . . . . . . . 402
Using COM with PHP . . . . . . . . . . . . . . . . . . . . . . . 404
vii
Table of Contents
Table of Contents
Chapter 11: PHP’s Command-Line Interface 417
Testing Your Installation . . . . . . . . . . . . . . . . . . . . 418
Executing Bits of Code . . . . . . . . . . . . . . . . . . . . . . 422
Creating a Command-Line Script . . . . . . . . . . . . 424
Running a Command-Line Script . . . . . . . . . . . . 428
Working with Command-Line Arguments . . . . 432
Taking Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437

Chapter 12: Using PEAR 443
Using Benchmark . . . . . . . . . . . . . . . . . . . . . . . . . . 444
Using HTML_QuickForm . . . . . . . . . . . . . . . . . . . 456
Using Mail_Mime . . . . . . . . . . . . . . . . . . . . . . . . . . 469
Chapter 13: Ajax 481
Introduction to Ajax . . . . . . . . . . . . . . . . . . . . . . . . 482
A Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . 484
Full-Fledged Ajax . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
Debugging Ajax Applications . . . . . . . . . . . . . . . . 523
Chapter 14: XML and PHP 529
What Is XML? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
XML Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
Attributes, Empty Elements, and Entities . . . . . 536
Document Type Definitions . . . . . . . . . . . . . . . . . 540
Parsing XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
Creating an RSS Feed . . . . . . . . . . . . . . . . . . . . . . . 562
Index 569
viii
Table of Contents
Table of Contents
If you’re looking at this book, then I probably don’t need to tell you how great PHP is.
Presumably, since you’re perusing the pages of an advanced text on the topic, you are
already using PHP for developing dynamic Web sites. Maybe you’ve been doing so for
a couple of years, perhaps just a couple of months. You could have learned PHP on your
own, in a class, or by reading one of the many excellent books on the subject. (I’m
referring not just to my own, of course!) Whatever the case, with some experience
under your belt, you probably don’t want another “here’s how to use PHP and isn’t it
swell” book. What you probably want to learn is how to use PHP more efficiently, more
securely, faster, and all-around better than you already are. If so, you’ve found the
right book.

In this humble author’s (or not-so-humble author’s) opinion, advanced PHP is about
learning: how to do different things, how to improve upon the basic things, and about
technologies that intersect with PHP. In short, you know how to make a dynamic Web
site with PHP, but you’d like to know how to make a better Web site, with every possible
meaning of “better.” That’s the approach I’ve taken in writing this book. I’ve not set
out to blow your mind discussing esoteric idiosyncrasies the language has, rewriting
the PHP, MySQL, or Apache source code, or making theoretically interesting but
practically useless code. In short, I present to you several hundred pages of beyond-the-
norm but still absolutely necessary (and often cool) tips and techniques.
ix
Introduction
i
Introduction
About This Book
Simply put, I’ve tried to make this book’s
content accessible and useful for every
PHP programmer out there. As I suggest
in the introductory paragraphs, I believe
that “advanced” PHP is mostly a matter
of extended topics. You already possess
all the basic knowledge—you retrieve data-
base query results in your sleep—but want
to go further. This may mean learning object-
oriented programming (OOP), using PEAR
(PHP Extension and Application Repository),
incorporating Ajax (Asynchronous JavaScript
and XML) into a site, or improving upon
aspects of your existing skill set.
My definition of advanced PHP program-
ming covers three loosely grouped skills:


Doing what you already do better, faster,
and more securely

Learning more sophisticated PHP tech-
niques

Doing standard things using PHP and
other technologies (like PEAR, Ajax,
or OOP)
This book can be divided into three sections,
corresponding to those skills. The first five
chapters cover advanced PHP knowledge
in general: programming techniques, Web
applications, databases, security, and e-com-
merce. They all cover information that the
average PHP programmer may not be famil-
iar with but should be able to comprehend,
providing useful code in the process.
The next six chapters focus on extending
your knowledge to areas of PHP with which
you might not be as familiar. Half of this sec-
tion goes over object-oriented programming
in great detail, from the fundamentals to
advanced topics to some real-world exam
ples.
The other three chapters are on different ways
you might use PHP: to communicate with
x
Introduction

Introduction
networked servers, to communicate with
the host server, or from a command-line
interface. The remaining three chapters each
deal with a specific technology tied into
PHP: PEAR, Ajax, and XML.
Two bonus chapters, “Image Generation” and
“Creating PDFs”, can be downloaded from
Peachpit’s Web site. Those two chapters,
which are available for free, provide another
100 pages of content showing how PHP ties
into related, and very useful, technologies.
Visit
www.peachpit.com/title/0321376013
to learn how to register this book and
download the chapters.
Most examples used in this book are intended
to be applicable in the real world, omitting
the frivolous code you might see in other
books, tutorials, and manuals. I focus as much
on the philosophies involved as on the coding
itself so that, in the end, you will come away
with not just how to do this or that but also
how to apply the overarching mentality to
your own, individual projects.
Unlike with most of my other books, I do
not expect that you’ll necessarily read this
book in sequential order, for the most part.
Some chapters do assume that you’ve read
others, like the object-oriented ones, which

have a progression to them. Some later
chapters also reference examples completed
in earlier ones. If you read the later ones
first, you’ll just need to quickly hop over to
the earlier ones to generate whatever data-
base or scripts the later chapter requires.
Finally, I’ll be using XHTML in my scripts
instead of HTML. I’ll also use some CSS, as
warranted. I do not discuss either of these
subjects in this book (and, to be frank, may
not adhere to them perfectly). If you are not
already familiar with the subjects, you should
look at some online resources or good books
(such as Elizabeth Castro’s excellent Visual
QuickStart Guides) for more information.
xi
Introduction
Introduction
What’s new in this edition
The most important change in this edition
of the book is that every bit of code has been
updated, rewritten, or replaced to ensure
100 percent compatibility with PHP 5. Many
of the examples have also been modified
to take advantage of features added to the
language.
What is also new is my approach. The first
edition of this text was the second book I
ever wrote. I’ve learned a lot since then, both
in terms of PHP and in terms of what read-

ers expect in a book. A lot of my valuable
experience in this latter category comes
from the constant interactions with other
readers through email and my supporting
forums (
www.DMCInsights.com/phorum/
). A
fair amount of material is therefore based
upon frequently asked questions I see.
How this book compares to my
others
Those readers who have come to this book
from my PHP for the World Wide Web: Visual
QuickStart Guide may find themselves in a
bit over their heads. This book does assume
comfort with standard PHP programming,
in particular debugging your own scripts.
I’m not suggesting you put this book down,
but if you find it goes too fast for you, or
assumes knowledge you don’t currently pos-
sess, you may want to check out my PHP
and MySQL for Dynamic Web Sites: Visual
QuickPro Guide instead.
If you have read the PHP and MySQL book,
or the first edition of this one, I’m hoping
that you’ll find this to be a wonderful addi-
tion to your library and skill set.
xii
Introduction
Introduction

About PHP 5
Although version 5 of PHP has been out
since July 2004 (when the first non-beta
version was released), there are still a large
number of servers running older versions
of PHP, particularly outside of the United
States. This book does assume you’re using
PHP 5, although some examples will work
with older versions of the language.
The most important change in PHP 5,
with respect to this book, is the completely
different object model and syntax. Object-
oriented programming in PHP 4 is a rather
watered-down concept, really not worth
using in comparison to PHP 5’s OOP. The
object-oriented chapters use PHP 5 syntax
exclusively, and that code will not work on
older versions of the language.
In addition, PHP 5 added support for the
Improved MySQL extension, designed for
use with MySQL 4.1 or later. With only one
or two exceptions, I use these Improved
MySQL functions instead of the older, “regu-
lar” MySQL functions. If your PHP installa-
tion (or MySQL installation) does not sup-
port these functions, you’ll need to change
the code accordingly.
xiii
Introduction
Introduction

What You’ll Need
Just as this book assumes that you already
possess the fundamental skills to program in
PHP (and, more important, to debug it when
things go awry), it also assumes that you
already have everything you need to follow
along with the material. For starters, this
means a PHP-enabled server. At the time of
this writing, the latest version of PHP was
5.2, and much of the book depends upon
your using at least PHP 5.0.
Along with PHP, you’ll often need a database
application. I use MySQL for the examples,
but you can use anything. And, for the scripts
in some of the chapters to work—particularly
the last five—your PHP installation will have
to include support for the corresponding
technology, and that technology’s library
may need to be installed, too. Fortunately
PHP 5 comes with built-in support for many
advanced features. If the scripts in a par-
ticular chapter require special extensions,
that will be referenced in the chapter’s intro-
duction. This includes the few times where
I ma
ke use of a PEAR or PECL class. Nowher
e
in this book will I discuss installation, though,
as I expect you should already know or have
accomplished that.

As with any issue, should you have questions
or problems, you can always search the Web
or post a message in my support forums for
assistance.
Beyond PHP, you need the things you should
already have: a text editor or IDE, an FTP
application (if using a remote server), and a
Web browser. All of the code in this book
has been tested on both Windows XP and
Mac OS X; you’ll see screen shots in both
operating systems.
xiv
Introduction
Introduction
Support Web Site
I have developed a Web site to support this
book, available at
www.DMCinsights.com/
phpvqp2/
. This site:

Has every script available for download

Has the SQL commands available for
download

Has extra files, as necessary, available
for download

Lists errors that have been found in

the book

Has a support forum where you can get
help or assist others

Provides a way to contact me directly
When using this site, please make sure
you’ve gone to the correct URL (the book’s
title and edition are plastered everywhere).
Each book I’ve written has its own support
area; if you go to the wrong one, the down-
loadable files won’t match those in the book.
Two bonus chapters, “Image Generation”
and “Creating PDFs,” can be downloaded
for free. Visit
www.peachpit.com/title/
0321376013
to learn how to register this
book and access the chapters.
xv
Introduction
Introduction
This page intentionally left blank
At the most basic level good programming is determined by whether or not an appli-
cation or script works as intended. This is where the beginning programmer will leave
things, and there is nothing wrong with that. However, the advanced programmer
will work past that point, striving toward improved efficiency, reliability, security,
and portability. This book teaches you how to develop the skills of an advanced PHP
programmer.
One thing the advanced PHP programmer does better than the beginner is learning to

take advantage of more obscure or harder-to-comprehend features of the language. For
example, while you probably already know how to use arrays, you may not have mas-
tered multidimensional arrays: creating them, sorting them, and so on. You have writ-
ten your own functions by this point but may not understand how to use recursion and
static variables. Issues like these will be discussed as well as other beyond-the-basics
concepts, like the heredoc syntax and the
printf()
/
sprintf()
family of functions.
1
Advanced
PHP Techniques
1
Advanced PHP techniques
Multidimensional Arrays
Because of their power and flexibility, arrays
are widely used in all PHP programming. For
advanced uses, the multidimensional array
often solves problems where other variable
types just won’t do.
For the first of the two examples, I’ll demon-
strate how to sort a multidimensional array.
It’s a common question users have and isn’t
as hard as one might think. For the second
example, I’ll create a database-driven to-do
list, which can have limitless dimensions
(Figure 1.1).
Sorting multidimensional arrays
Sorting arrays is easy using PHP, thanks to

the
sort()
,
ksort()
, and related functions.
You can sort a one-dimensional array by key,
by value, in reverse order, etc. But these func-
tions will not work on multidimensional
arrays (not as you’d probably like, at least).
Say you have an array defined like so:
$a = array (
array (‘key1’ => 940, ‘key2’ => ‘blah’),
array (‘key1’ => 23, ‘key2’ => ‘this’),
array (‘key1’ => 894, ‘key2’ => ‘that’)
);
This is a simple two-dimensional array (an
array whose elements are also arrays) that
you might need to sort using
key1
(a numeric
sort) or
key2
(an alphabetical sort). To sort a
multidimensional array, you define your own
sort function and then tell PHP to use that
function via the
usort()
,
uasort()
, or

uksort()
function. The function you define
must take exactly two arguments and return
a value indicating which should come first.
Figure 1.2 The multidimensional array
sorted by numeric value (
key1
).
Figure 1.1 One use of multidimensional
arrays will be to create a nested to-do
list.
2
Chapter 1
Multidimensional Arrays
Figure 1.4 An alphabetical sort on
the example array using
key2
.
Figure 1.3 By printing out the values
of
$x[‘key1’]
and
$y[‘key1’]
, one
can see how the user-defined sorting
function is invoked.
To sort the preceding array on the first key,
the sorting function would like this:
function mysort1 ($x, $y) {
return ($x[‘key1’] > $y[‘key1’]);

}
Then the PHP code would use this function
by doing:
usort ($a, ‘mysort1’);
Figure 1.2 shows the same array at this
point.
PHP will continue sending the inner arrays
to this function so that they may be sorted. If
you want to see this in detail, print the values
being compared in the function (Figure 1.3).
The
usort()
function sorts by values and does
not maintain the keys (for the outermost
array). If you used
uasort()
, the keys would
be maintained, and if you used
uksort()
, the
sort would be based upon the keys.
To sort on the second key in the preceding
example, you would want to compare two
strings. That code would be (Figure 1.4
shows the result):
function mysort2 ($x, $y) {
return strcasecmp($x[‘key2’],

$y[‘key2’]);
}

usort ($a, ‘mysort2’);
Or you could just use
strcmp()
, to perform a
case-sensitive sort.
To see this in action for yourself, let’s run
through an example.
3
Advanced PHP Techniques
Multidimensional Arrays
To sort a multidimensional array:
1.
Create a new PHP script in your text edi-
tor or IDE, starting with the HTML code
(Script 1.1).
<!DOCTYPE html PUBLIC “-//W3C//

DTD XHTML 1.0 Transitional//EN”
“ />➝
xhtml1-transitional.dtd”>
<html xmlns=” />➝
xhtml” xml:lang=”en” lang=”en”>
<head>
<meta http-equiv=”content-type”

content=”text/html; charset=

iso-8859-1” />
<title>Sorting Multidimensional


Arrays</title>
</head>
<body>
<?php # Script 1.1 - sort.php
2.
Define a multidimensional array.
$students = array (
256 => array (‘name’ => ‘Jon’,

‘grade’ => 98.5),
2 => array (‘name’ => ‘Vance’,

‘grade’ => 85.1),
9 => array (‘name’ => ‘Stephen’,

‘grade’ => 94.0),
364 => array (‘name’ => ‘Steve’,

‘grade’ => 85.1),
68 => array (‘name’ => ‘Rob’,

‘grade’ => 74.6)
);
The outer array,
$students
, has five ele-
ments, each of which is also an array. The
inner arrays use the student’s ID for the
key (a made-up value) and store two
pieces of data: the student’s name and

their grade.
continues on page 6
4
Chapter 1
Multidimensional Arrays
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 " />3 <html xmlns=" xml:lang="en" lang="en">
4 <head>
5 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
6 <title>Sorting Multidimensional Arrays</title>
7 </head>
8 <body>
9 <?php # Script 1.1 - sort.php
10
11 /* This page creates a multidimensional array
12 * of names and grades.
13 * The array is then sorted twice:
14 * once by name and once by grade.
15 */
16
17 // Create the array:
18 // Array structure:
19 // studentID => array ('name' => 'Name', 'grade' => XX.X)
20 $students = array (
21 256 => array ('name' => 'Jon', 'grade' => 98.5),
22 2 => array ('name' => 'Vance', 'grade' => 85.1),
23 9 => array ('name' => 'Stephen', 'grade' => 94.0),
24 364 => array ('name' => 'Steve', 'grade' => 85.1),
25 68 => array ('name' => 'Rob', 'grade' => 74.6)
26 );

27
28 // Name sorting function:
29 function name_sort ($x, $y) {
30 return strcasecmp($x['name'], $y['name']);
31 }
32
33 // Grade sorting function:
34 // Sort in DESCENDING order!
35 function grade_sort ($x, $y) {
36 return ($x['grade'] < $y['grade']);
37 }
38
39 // Print the array as is:
40 echo '<h3>Array As Is</h3><pre>' . print_r($students, 1) . '</pre>';
41
42 // Sort by name:
43 uasort ($students, 'name_sort');
44
45 // Print the array now:
46 echo '<h3>Array Sorted By Name</h3><pre>' . print_r($students, 1) . '</pre>';
47
48 // Sort by grade:
49 uasort ($students, 'grade_sort');
50
51 // Print the array now:
52 echo '<h3>Array Sorted By Grade</h3><pre>' . print_r($students, 1) . '</pre>';
53
54 ?>
55 </body>
56 </html>

Script 1.1 This script defines a two-dimensional array, which is then sorted based upon the inner array values.
5
Advanced PHP Techniques
Multidimensional Arrays
3.
Define the name sorting function.
function name_sort ($x, $y) {
return strcasecmp($x[‘name’],

$y[‘name’]);
}
The
strcasecmp()
function returns a
number—negative, 0, or positive—indi-
cating how similar two strings are. If a
negative value is returned, the first string
comes before the second alphabetically; if
a positive value is returned, the second
string comes first. If 0 is returned, the
strings are the same.
4.
Define the grade sorting function.
function grade_sort ($x, $y) {
return ($x[‘grade’] <

$y[‘grade’]);
}
This example is like the demo in the
introduction to these steps. One signifi-

cant difference is that I want to perform
a descending sort, so that the highest
grades are listed first. This is easily
accomplished: change the comparison
operator from greater than to less than.
5.
Print the array as it’s initially defined.
echo ‘<h3>Array As Is</h3><pre>’ .

print_r($students, 1) . ‘</pre>’;
For improved legibility, I’ll use the
<pre>
tags and
print_r()
to quickly reveal the
arrays’ structure and values.
6.
Sort the array by name and print the
results.
uasort ($students, ‘name_sort’);
echo ‘<h3>Array Sorted By

Name</h3><pre>’ .

print_r($students, 1) . ‘</pre>’;
Here the
uasort()
function is used so
that the keys—the student IDs—are not
lost. Figure 1.5 shows the result if just

usort()
was used instead.
Figure 1.5 Failure to use
uasort()
would
cause the keys, which store meaningful
values (see Script 1.1), to be lost.
6
Chapter 1
Multidimensional Arrays
Figure 1.6 The initial array and sorted
by name.
7.
Sort the array by grade and print the
results.
uasort ($students, ‘grade_sort’);
echo ‘<h3>Array Sorted By

Grade</h3><pre>’ .

print_r($students, 1) . ‘</pre>’;
7
Advanced PHP Techniques
Multidimensional Arrays
8.
Complete the page.
?>
</body>
</html>
9.

Save the file as
sort.php
, place it in your
Web directory, and test in your Web
browser (Figures 1.6 and 1.7).
Figure 1.7 The array sorted by grade, in
descending order (this is the same Web
page as in Figure 1.6, but it couldn’t all
fit in one screenshot).
Database-driven arrays
If you think about it, most database queries
return a multidimensional array (Figure 1.8).
If the query results are immediately sent to
the Web browser one at a time, the multidi-
mensional structure doesn’t add any compli-
cation to your code. However, if you need to
do something more elaborate with the results,
you’ll need a way to comprehend and man-
age the nested structure.
For this example, I want to create a database-
driven, Web-based to-do list system. If the
to-do list were one-dimensional, this wouldn’t
be that hard. But the list should be nestable,
where each item can have multiple steps.
The result will be a tree-like structure, where
each branch can have its own offshoots
(Figure 1.9).
Figure 1.8 Selecting multiple columns from multiple
rows in a database results in a multidimensional
array.

8
Chapter 1
Multidimensional Arrays
Figure 1.9 How a nested to-do list looks as a tree.

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×