如何在PHP中创建具有键值对的数组?
PHP为我们提供了一种特殊类型的数组,称为关联数组,它允许我们创建具有键值对的数组。创建关联数组的语法如下:
语法 1:使用 array() 构造函数
$arrayVariable = array(
key1 => value1,
key2 => value2,
key3 => value3,
...
keyN => valueN,
);
语法 2:使用速记符号
$arrayVariable = [
key1 => value1,
key2 => value2,
key3 => value3,
...
keyN => valueN,
];
笔记:
- 最后一个键值对后面的逗号是可选的。
- Key可以是整数或字符串类型。
- 值可以是任何有效类型。
- 如果Key的类型不是字符串或整数,它将根据Key的类型转换为字符串或整数。
示例 1:使用 array() 构造函数
"Facebook, Inc. is an online social media and
social networking service company.",
"Twitter" =>
"Twitter is a microblogging and social networking service on
which users post and interact with messages known as tweets.",
"LinkedIn" =>
"LinkedIn is a business and employment-oriented service
that operates via websites and mobile apps.");
$websites["Instagram"] = "Instagram is a photo and video-sharing
social networking service owned by Facebook, Inc.";
foreach ($websites as $key => $value) {
echo "$key: $value
";
}
?>
输出:
示例 2:使用速记符号
"Facebook, Inc. is an online social
media and social networking service company.",
"Twitter" => "Twitter is a microblogging and social networking service
on which users post and interact with messages known as tweets.",
"LinkedIn" => "LinkedIn is a business and
employment-oriented service that operates via websites and mobile apps."];
$websites[
"Instagram"] = "Instagram is a photo and video-sharing
social networking service owned by Facebook, Inc.";
foreach ($websites as $key => $value) {
echo "$key: $value
";
}
?>
输出: