PHP Arrays

จาก Wiki2

ข้ามไปที่: นำทาง, สืบค้น

เนื้อหา

Create Arrays by assignment value

$customers[1] = “Sam Smith”;
$customers[2] = “Sue Jones”;
$customers[3] = “Mary Huang”;


$capitals[‘CA’] = “Sacramento”;
$capitals[‘TX’] = “Austin”;
$capitals[‘OR’] = “Salem”;

same as

$capitals = array ( “CA” => “Sacramento”, “TX” => “Austin”, “OR” => “Salem” );


$streets[] = “Elm St.”;
$streets[] = “Oak Dr.”;
$streets[] = “7th Ave.”;

same as

$streets = array ( “Elm St.”,”Oak Dr.”,”7th Ave.”);


$streets = array ( 12 => “Elm St.”,”Oak Dr.”,”7th Ave.”);

same as

$streets[12] = Elm St.
$streets[13] = Oak Dr.
$streets[14] = 7th Ave.


$years = range(2001, 2010);

same as

$years[0]= 2001;
$years[1]= 2002;
. . .
$years[8]= 2009;
$years[9]= 2010;


$reverse_letters = range(“z”, “a”);

same as

$reverse_letters[0]=z
$reverse_letters[1]=y
. . .
$reverse_letters[24]=b
$reverse_letters[25]=a

Viewing Arrays

print_r($customers);

output as

Array
(
       [1] => Sam Smith
       [2] => Sue Jones
       [3] => Mary Huang
)

var_dump($customers);

output as

array(3) {
   [1]=>
   string(9) “Sam Smith”
   [2]=>
   string(9) “Sue Jones”
   [3]=>
   string(10) “Mary Huang”
}

Modifying Arrays

by re-assign

$capitals[‘TX’] = “Big Springs”;

Copy array

$customerCopy = $customers;

Removing value

unset($colors[3]);

unset($colors);

Sorting Arrays

sort($arrayname);

asort($capitals);

rsort($capitals);


Sort Statement What It Does

  1. sort($arrayname) Sorts by value; assigns new numbers as the keys.
  2. asort($arrayname) Sorts by value; keeps the same key.
  3. rsort($arrayname) Sorts by value in reverse order; assigns new num-bers as the keys.
  4. arsort($arrayname) Sorts by value in reverse order; keeps the same key.
  5. ksort($arrayname) Sorts by key.
  6. krsort($arrayname) Sorts by key in reverse order.
  7. usort($arrayname, Sorts by a function (see Chapter 8 for information functionname) on functions).
  8. natsort($arrayname) Sorts mixed string/number values in natural order. For example, given an array with values day1, day5, day11, day2, it sorts into the following order: day1,day2, day5, day11. The previous sort functions sort the array into this order: day1, day11, day2, day5.

Using Arrays in Statements

$CAcapital = $capitals[‘CA’];
echo $CAcapital ;

output

Sacramento


echo $capitals[‘TX’];

output

Austin


echo “The capital of Texas is {$capitals[‘TX’]}”;

output

The capital of Texas is Austin


รับข้อมูลจาก "http://www.noklek.com/wiki2/index.php/PHP_Arrays"
เครื่องมือส่วนตัว