PHP中的关联数组详细介绍

2021年3月11日17:00:21 发表评论 920 次浏览

关联数组用于存储键值对。例如, 要将学生不同学科的分数存储在一个数组中, 数字索引数组将不是最佳选择。取而代之的是, 我们可以使用相应主题的名称作为关联数组中的键, 而值将是它们各自获得的标记。

例子:

这里

array()

函数用于创建关联数组。

<?php   
/* First method to create an associate array. */
$student_one = array ( "Maths" =>95, "Physics" =>90, "Chemistry" =>96, "English" =>93, "Computer" =>98); 
    
/* Second method to create an associate array. */
$student_two [ "Maths" ] = 95; 
$student_two [ "Physics" ] = 90; 
$student_two [ "Chemistry" ] = 96; 
$student_two [ "English" ] = 93; 
$student_two [ "Computer" ] = 98; 
    
/* Accessing the elements directly */
echo "Marks for student one is:\n" ; 
echo "Maths:" . $student_two [ "Maths" ], "\n" ; 
echo "Physics:" . $student_two [ "Physics" ], "\n" ; 
echo "Chemistry:" . $student_two [ "Chemistry" ], "\n" ; 
echo "English:" . $student_one [ "English" ], "\n" ; 
echo "Computer:" . $student_one [ "Computer" ], "\n" ; 
?>

输出如下:

Marks for student one is:
Maths:95
Physics:90
Chemistry:96
English:93
Computer:98

遍历关联数组:

我们可以使用循环遍历关联数组。我们可以通过两种方式遍历关联数组。首先通过使用

对于

循环, 其次使用

前言

.

例子:

这里

array_keys()

函数用于查找赋予它们的索引名称, 以及

计数()

函数用于对关联数组中的索引数进行计数。

<?php 
    
/* Creating an associative array */
$student_one = array ( "Maths" =>95, "Physics" =>90, "Chemistry" =>96, "English" =>93, "Computer" =>98); 
    
    
/* Looping through an array using foreach */
echo "Looping using foreach: \n" ; 
foreach ( $student_one as $subject => $marks ){ 
     echo "Student one got " . $marks . " in " . $subject . "\n" ; 
} 
   
/* Looping through an array using for */
echo "\nLooping using for: \n" ; 
$subject = array_keys ( $student_one ); 
$marks = count ( $student_one );  
    
for ( $i =0; $i < $marks ; ++ $i ) { 
     echo $subject [ $i ] . ' ' . $student_one [ $subject [ $i ]] . "\n" ; 
} 
?>

输出如下:

Looping using foreach: 
Student one got 95 in Maths
Student one got 90 in Physics
Student one got 96 in Chemistry
Student one got 93 in English
Student one got 98 in Computer

Looping using for: 
Maths 95
Physics 90
Chemistry 96
English 93
Computer 98

创建混合类型的关联数组

<?php   
/* Creating an associative array of mixed types */
$arr [ "xyz" ] = 95; 
$arr [100] = "abc" ; 
$arr [11.25] = 100; 
$arr [ "abc" ] = "pqr" ; 
    
/* Looping through an array using foreach */
foreach ( $arr as $key => $val ){ 
     echo $key . "==>" . $val . "\n" ; 
}  
?>

输出如下:

xyz==>95
100==>abc
11==>100
abc==>pqr

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: