[英]Getting the values of a multidimensional array where key value is in another array
我有一系列课程:
Array
(
[0] => BIOL-1108
[1] => BIOL-1308
[2] => BIOL-2401
[3] => BIOL-2402
)
以及一个多维的已完成课程数组,如下所示:
Array
(
[course] => Array
(
[0] => Array
(
[course] => BIOL-2401
[title] => BIOL-2401 - Human Anatomy & Physiology I
[grade] => A
)
[1] => Array
(
[course] => HIST-1301
[title] => HIST-1301 - History of the U.S. I
[grade] => B
)
[2] => Array
(
[course] => MATH-0303
[title] => MATH-0303 - Intermediate Algebra
[grade] => F
)
[3] => Array
(
[course] => BIOL-1108
[title] => BIOL-1108 - Life Science I Lab
[grade] => B
)
[4] => Array
(
[course] => BIOL-1308
[title] => BIOL-1308 - Life Science I
[grade] => C
)
)
)
如果它存在于第一个数组中,我只想回显课程、标题和成绩。 我想我需要一个 foreach 循环,但我被卡住了。
您走在正确的轨道上,因为您需要遍历多维数组值,然后查看课程是否在您的课程数组中。 这可以通过将 foreach 与 in_array 函数结合使用来完成。
<?php
$courses = array('BIOL-1108', 'BIOL-1308', 'BIOL-2401','BIOL-2402');
$completed_courses = array(
'course' => array(
array(
'course' => 'BIOL-2401',
'title' => 'BIOL-2401 - Human Anatomy & Physiology I',
'grade' => 'A'
),
array(
'course' => 'HIST-1301',
'title' => 'HIST-1301 - History of the U.S. I',
'grade' => 'B'
),
array
(
'course' => 'MATH-0303',
'title' => 'MATH-0303 - Intermediate Algebra',
'grade' => 'F'
),
array
(
'course' => 'BIOL-1108',
'title' => 'BIOL-1108 - Life Science I Lab',
'grade' => 'B'
),
array
(
'course' => 'BIOL-1308',
'title' => 'BIOL-1308 - Life Science I',
'grade' => 'C'
)
)
);
foreach( $completed_courses['course'] as $curr ){
if(in_array($curr['course'], $courses)) {
echo 'COURSE : ' . $curr['course'] . PHP_EOL;
echo 'TITLE : ' . $curr['title'] . PHP_EOL;
echo 'GRADE : ' . $curr['grade'] . PHP_EOL;
}
}
您可能正在寻找array_flip
函数,而不是很简单。
<?php
$courses = [
'BIOL-1108',
'BIOL-1308'
];
$completed = [
'course' => [
[
'course' => 'BIOL-1108',
'title' => 'title',
'grade' => 'C'
],
[
'course' => 'BIOL-1308',
'title' => 'title',
'grade' => 'C'
],
[
'course' => 'BIOL-1408',
'title' => 'title',
'grade' => 'C'
]
]
];
$courses = array_flip($courses);
foreach ($completed['course'] as $row) {
if (!isset($courses[$row['course']])) {
echo $row['course'] . '<BR>'; // returns BIOL-1408 in my example
}
}
您可以遍历数组(假设变量名称)并使用in_array
检查课程标题是否存在。
foreach($user['course'] as $course):
if(in_array($course['title'], $completedCourses)):
printf('Title: %s, Grade: %s', $course['title'], $course['grade']);
endif;
endforeach;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.