在第二(以下)的代碼段,在內foreach
循環(也就是foreach
循環嵌套在另一個foreach
循環),則$value
對應於$studentCoursesStudied
的元件,而不是$studentCoursesStudied
數組本身,對吧?
的correct way訪問$studentCoursesStudied
陣列的元素的值將是:
$studentCoursesStudied[$key]
但是他們正在訪問像
$value['an-element-name/key']
其中$studentCoursesStudied
陣列的每個元素的值$ value對應於數組的一個元素,而不是數組本身!爲什麼?
背景: 我讀通過別人學習寫一個PHP腳本,我不明白他們是如何在一個點訪問關聯數組中的值。所以我寫了這個示例代碼來問這個問題。
這是Student
類,學生有一個包含關聯數組的名稱爲recordCoursesStudied
的屬性。
class Student {
public $studentName;
public $studentAge;
public $studentCoursesStudied = null;
function __construct($studentName, $studentGpa) {
$this->studentName = $studentName;
$this->studentGpa = $studentGpa;
}
function recordCoursesStudied ($courseName, $courseNumber, $creditHours, $maxMarks, $courseType) {
$this->studentCoursesStudied[] = array(
'courseName' => $courseName;
'courseNumber' => $courseNumber;
'creditHours' => $creditHours;
'maxMarks' => $maxMarks;
'courseType' => $courseType;
);
}
}
然後我們想從另一個類Whatever
從它的方法newCourseRecord
訪問recordCoursesStudied
的元素。
注:在塊註釋內foreach
循環之後,我已經寫了相同的片段,以更好的名稱來把事情說清楚。
class Whatever {
private $students;
private $currentStudent;
function __construct() {
$this->newStudent('Zarah', 3.4);
$this->newCourseRecord('DBMS', 'BR223', 3, 100, 'Core');
$this->doTheWork();
}
function newStudent($studentName, $studentGpa) {
$this->students[$studentName] = new Student($studentName, $studentGpa);
$this->currentStudent = $studentName;
}
function newCourseRecord($courseName, $courseNumber, $creditHours, $maxMarks, $courseType) {
$this->students[$this->studentName]->recordCoursesStudied($courseName, $courseNumber, $creditHours, $maxMarks, $courseType);
}
function doTheWork() {
...
foreach ($this->students as $key=>$value) {
...
foreach($value->studentCoursesStudied as $key=>$value) { /****************************/
...
//Echo each property of $studentCoursesStudied.
someOtherFunction($value['courseName'], $value['courseNumber'], $value['creditHours'], $value['maxMarks'], $value['courseType']);
...
}
...
}
/*foreach ($this->students as $studentKey=>$studentValue) {
...
foreach($studentValue->studentCoursesStudied as $courseKey=>$courseValue) { /****************************/
...
//Echo each property of $studentCoursesStudied.
/*someOtherFunction($courseValue['courseName'], $courseValue['courseNumber'], $courseValue['creditHours'], $courseValue['maxMarks'], $courseValue['courseType']);
...
}
...
}*/
...
}
}
在給定的代碼,在foreach
環路由*
的要點之外,他們已經通過執行類似訪問的Student::studentCoursesStudied
數組中的值:
$value-of-an-element-in-array['key-of-an-element-in-array']
但不應關聯的元素數組訪問像name-of-array['key-of-an-element-in-array']
?
我有點困惑,因爲你[不應該能夠訪問那個私人財產](https://eval.in/318112)直接 –
@scrowler嘿,我只是寫這個匆忙演示問題。我將更改訪問修飾符(但也可能有其他一些小錯誤) – Solace
您在第二課中有錯誤。你還沒有在'newCourseRecord'方法中設置'$ this-> studentName'。你最好發貼原始代碼 – winston86