[英]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.