close

1.關聯陣列Associatively Array

關聯陣列Associatively Array,又稱Map,他是將陣列內之key依照以下之方式指定value之陣列

'key' => value

可以指定所有陣列內所有key之value,而不另外設一相應陣列

EX:

<?php
// This is an array using integers as the indices.
// Add 'BMW' as the last element in the array!
$car = array(2012, 'blue', 5, "BMW");

// This is an associative array.
// Add the make => 'BMW' key/value pair!
$assocCar = array('year' => 2012,
'colour' => 'blue',
'doors' => 5,
"make"=>"BMW");

// This code should output "BMW"...
echo $car[3];
echo '<br />';

// ...and so should this!
echo $assocCar['make'];
?>

2.關聯陣列疊代要用foreach

以1.的範例來做說明

echo $car[0] // 2012

但是對Associatively Array來說應該為

echo $assocCar['year']//2012

所以對於Associatively Array來說,沒辦法使用for迴圈,所以必須使用foreach迴圈

EX:

$me = array('hair' => 'black',
            'skin tone' => 'light');
foreach ($me as $feature(也就是key)=>$colour(也就是value)) {
  echo 'My ' . $feature . ' is ' . $colour . '. ';
}

 

3.多維陣列

在一陣列中多加其他陣列

EX:

$deck = array(array('2 of Diamonds', 2),
                      array('3 of Diamonds', 3),
                      array('5 of Diamonds', 5),
                      array('7 of Diamonds', 7));


echo 'You have the ' . $deck[2][0](第一個陣列中之第三個子陣列)(所指之子陣列的第一項) . '!'; // You have the 7 of Diamonds!
arrow
arrow
    全站熱搜

    Joseph Lin 發表在 痞客邦 留言(0) 人氣()