使用动态键字符串检索对象变量

时间:2013-06-21 19:52:46

标签: php reference

我有一个名为“required”的PHP对象。这个“必需”字段是一个嵌套数组。我想用动态字符串(对于属性名称和数组索引)从此对象中检索所需的键。我怎样才能做到这一点?

$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 :: $ required [courses] [lessons] [lesson_name_required]

3 个答案:

答案 0 :(得分:2)

$desiredKey的值为required[courses][lessons][lesson_name_required]。这不作为财产存在。现在$desiredKey只是一个字符串。 PHP不解释字符串来访问数组属性。您还忘记了数组键周围的引号。您可以像这样访问所需的值:

$desiredValue = $myObj->required["courses"]["lessons"]["lesson_name_required"];

答案 1 :(得分:2)

我假设您知道如何正确访问对象/数组,并且正在尝试动态生成所需值的路径。下面的代码将允许您传递一个字符串,并过滤该字符串中多个键的对象。

<?php
$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";

// Set our searchObject to $myObj->required using Variable Variables
$searchObject = $myObj->$desiredKeyAttributePart;
// Match all of the keys in our string
preg_match_all('/\[(.*?)\]/', $desiredKeyArrayPart, $keyMap);
// Foreach key that we found
foreach ($keyMap[1] as $key) {
  // Change our $searchObject to the new key's value
  $searchObject = $searchObject[$key];
}
// We found our object
var_dump($searchObject);

答案 2 :(得分:0)

替换它:

$desiredKeyArrayPart = "[courses][lessons][lesson_name_required]";
$desiredKeyAttributePart = "required";
$desiredKey = $desiredKeyAttributePart . $desiredKeyArrayPart;

// Get the value (Should return 1)
$desiredValue = $myObj->$desiredKey;

由此:

$desiredValue = $myObj->required['courses']['lessons']['lesson_name_required'];

你尝试这样做的方式是行不通的。此外,引用数组值是可取的,以避免警告。