简体   繁体   English

将对象转换为数组并在php中检索

[英]convert object to array and retrieve in php

I have result like below. 我得到如下结果。

   stdClass Object
    (
      [Test_Result] => stdClass Object
        (
          [Test] => Array
            (
                [0] => stdClass Object
                    (

                        [name] => test1
                    )

                [1] => stdClass Object
                    (

                        [name] => test2
                    )

                [2] => stdClass Object
                    (

                        [name] => test3
                    )

                [3] => stdClass Object
                    (

                        [name] => test4
                    )

                [4] => stdClass Object
                    (

                        [name] => test5
                    )

            )

      )

 )

I am trying to retrieve name and add them as option values for select tag. 我试图检索名称并将其添加为选择标记的选项值。

I am expecting like below 我期望像下面

 <select id="names" name="names" class="required-entry select">
                <option value="" selected="selected">Please select...</option>
                <option value="test1">test1</option>
                <option value="test2">test2</option>
                <option value="test3">test3</option>
                <option value="test4">test4</option>
                <option value="test5">test5</option>
            </select>

How can i do it in PHP? 如何在PHP中做到这一点? Please anyone suggest me, How retrieve each values from the above result? 请有人建议我,如何从上述结果中检索每个值?

$object->Test_Result->Test is an array of objects that just have a name property. $ object-> Test_Result-> Test是仅具有name属性的对象数组。 If you just want that name property, run a map on that array to convert that array to just the names. 如果只需要name属性,请在该数组上运行一个映射,以将该数组转换为仅名字。

$names = array_map(function($item) {
    return $item->name;
}, $object->Test_Result->Test);

Read more on array_map here. 在这里阅读更多关于array_map的信息。

If your object is $obj , you can do it like this: 如果您的对象是$obj ,则可以这样操作:

echo '<select id="names" name="names" class="required-entry select">';
echo '<option value="" selected="selected">Please select...</option>';
foreach($obj->Test_Result->Test as $key => $value){
    echo '<option value="'.$value->name.'">'.$value->name.'</option>';
}
echo '</select>';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM