我遇到的问题是当我遍历多维数组时,一旦我掌握了多维数组中的技能,它就会输出:
Andrew Wiley
30
Game Designer
72000
Array
C++ Level Design Leadership
它同时显示了Array和C ++级别设计领导力。
我如何删除Array的输出并用C ++ Level Design Leadership技能替换它,而不同时打印两者?
$students = [
Andrew => [
fullName => Andrew Wiley,
age => 30,
jobTitle => Game Designer,
Salary => 72000,
skills => [C++, Level Design, Leadership]
]
];
foreach($students[Andrew] as $student) {
echo $student . <br>;
if($student == $students[Andrew][skills]) {
foreach($students[Andrew][skills] as $skill) {
echo $skill;
}
}
};
答案 0 :(得分:0)
您可以使用递归函数。
function printVariables($array,$level=1){
foreach($array as $value){
if(is_array($value)){
$level++;
printVariables($value,$level);
}else{
echo $level <= 2 ? "$value\n" : "$value ";
}
}
}
printVariables($students);
或序列化它...
foreach($students as $student){
echo json_encode($student,JSON_PRETTY_PRINT);
}
答案 1 :(得分:0)
像这样更新您的foreach:
foreach($students['Andrew'] as $student) {
echo $student . <br>;
if($student === $students['Andrew']['skills']
&& is_array($students['Andrew']['skills'])
&& count($students['Andrew']['skills']) > 0) {
echo implode(", ",$students['Andrew']['skills']);
}
}
输出:
C ++,关卡设计,领导力
这是什么:
echo
输出该字符串。 还要注意数组键周围的引号