我有一個名爲「required」的屬性的PHP對象。這個「required」字段是一個嵌套數組。我想用動態字符串(對於屬性名稱和數組索引)從此對象中檢索所需的鍵。我怎樣才能做到這一點?使用動態鍵字符串檢索對象變量
$myObj = new StdClass;
$myObj->required = array(
"name_required" => 1,
"courses" => array(
"course_name_required" => 1,
"lessons_required" => 1,
"lessons" => array(
"lesson_name_required" => 1,
"lesson_file_required" => 1,
"is_viewed_required" => 1,
),
),
);
// Desired Key I want to retrieve using dynamic strings.
$desiredKeyArrayPart = "[courses][lessons][lesson_name_required]";
$desiredKeyAttributePart = "required";
$desiredKey = $desiredKeyAttributePart . $desiredKeyArrayPart;
// Get the value (Should return 1)
$desiredValue = $myObj->$desiredKey;
我想返回的值1,但此引發運行時錯誤: PHP公告:未定義的屬性:stdClass的:: $所需[課程] [經驗] [lesson_name_required]
正是我在找的東西。謝謝! – Rainbard