英文:
how to put students into different arrays according to their age?
问题
在PHP中,可以使用switch
语句来更简洁地重写这种if...elseif...else代码块。以下是使用switch
语句的示例:
$age1 = array();
$age2 = array();
$age3 = array();
// Similarly arrays for ages 4,5,6,7,8,9 and 10.
switch($student_age) {
case 1:
$age1[] = $student_name;
break;
case 2:
$age2[] = $student_name;
break;
case 3:
$age3[] = $student_name;
break;
// Add cases for ages 4,5,6,7,8,9 and 10 here.
default:
// Handle the default case here.
break;
}
使用switch
语句可以更清晰地列出不同年龄段的情况,并且可以轻松添加更多的情况,以处理其他年龄。
英文:
What can be a better and easier way of writing this if...elseif...else code in PHP.
Suppose $student_name
and $student_age
are two variables.
$age1 = array();
$age2 = array();
$age3 = array();
//Similarly arrays for ages 4,5,6,7,8,9 and 10.
if($student_age == 1){
$age1[] = $student_name;
}
elseif($student_age == 2){
$age2[] = $student_name;
}
elseif($student_age == 3){
$age3[] = $student_name;
}
//Elseif loop continues for ages 4,5,6,7,8,9 and 10.
else{
...
}
答案1
得分: 2
使用适当的数据结构来存储数据,而不仅仅考虑变量名。
在PHP中,一个灵活的选项是array
,你可以将名字映射到年龄,因为你可以创建数组的数组(多维数组):
$age[$student_age][] = $student_name;
这里是一个学生年龄到学生名字列表的映射。
一般来说,最好的if/else是你不需要的情况。
英文:
Use a fitting data-structure for your data, not just think in variables names.
One flexible in PHP is array
and here you can map the names to the ages as you can create arrays of arrays (multidimensional arrays):
$age[$student_age][] = $student_name;
Here a map of student age to a list of the student names.
In general the best if/else is the one you don't have.
答案2
得分: 2
$ages = [];
// loop the inside Then
if (!isset($ages[$student_age])) {
$ages[$student_age] = [];
}
$ages[$student_age][] = $student_name;
英文:
Instead of having 10 arrays, this probably works better as 1 2-dimensional array.
$ages = [];
// Then inside the loop
if (!isset($ages[$student_age])) {
$ages[$student_age] = [];
}
$ages[$student_age][] = $student_name;
答案3
得分: 0
最简单的解决方法是定义一个多维数组来存储学生的年龄。根据年龄增加数组索引,然后根据年龄分配学生姓名。
<?php
$ages = [2 => [], 3 => [], 4 => []];
$ages[$student_age] = $student_name;
英文:
The simplest way to sort our the problem to define a multidimensional array for the student age. The array index can increased based on the ages and then assign student name according to the age
<?php
$ages = [2 => [], 3 => [], 4 => []];
$ages[$student_age] = $student_name;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论