📜  PHP的关联数组

📅  最后修改于: 2022-05-13 01:57:40.095000             🧑  作者: Mango

PHP的关联数组

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

例子:
这里array()函数用于创建关联数组。

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

遍历关联数组:
我们可以使用循环遍历关联数组。我们可以通过两种方式遍历关联数组。首先使用for循环,其次使用foreach

例子:
这里array_keys()函数用于查找赋予它们的索引名称, count()函数用于计算关联数组中索引的数量。



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

创建混合类型的关联数组

 $val){ 
    echo $key."==>".$val."\n"; 
}  
?> 
输出:
xyz==>95
100==>abc
11==>100
abc==>pqr

PHP是一种专门为 Web 开发设计的服务器端脚本语言。您可以按照此PHP教程和PHP示例从头开始学习PHP 。