我从数据库中取出一个对象,然后我转换了#39;它是数组,以便我可以使用foreach。
$my_obj = (array) json_decode( get_option('my_options') );
当我对其进行print_r
时,这会得到像这样的数组:
Array (
[0] => stdClass Object (
[settings] => stdClass Object (
[default] => 1
[header_title] => Separate title for this one!
[header_layout] => header_logo_centered
[fixed_header] => 1
[sticky_header] => 0
[transparent_header_transition] => 1
[select_menu] => centered-logo-header
[select_second_menu] => left-menu-header
[logo] =>
[retina_logo] => ...wp-content/uploads/2015/12/sample.jpg
[retina_logo_width] =>
[retina_logo_height] =>
[transparent_logo] =>
[transparent_retina_logo] =>
[transparent_retina_logo_width] =>
[transparent_retina_logo_height] =>
[background_image] => ...wp-content/uploads/2015/08/audiothumb1.jpg
[background_color] => #848484
[text_color] => #397509
[text_hover_color] =>
[transparent_text_color] =>
[transparent_text_hover_color] => #146051
[test_select] => test_option_3
[test_textarea] => This is a test for textarea....ghghfsd
[test_pages_dropdown] => 5452
[icon_number] => 1
[test_icons_icon_0] => s7-magic-wand
[test_icons_value_0] => test2
)
)
[1] => stdClass Object (
[settings] => stdClass Object (
[default] => 0
[header_title] => Test title here...
[header_layout] => header_layout_logo_left_magic_background
[fixed_header] =>
[sticky_header] =>
[transparent_header_transition] =>
[select_menu] =>
[select_second_menu] =>
[logo] =>
[retina_logo] =>
[retina_logo_width] =>
[retina_logo_height] =>
[transparent_logo] =>
[transparent_retina_logo] =>
[transparent_retina_logo_width] =>
[transparent_retina_logo_height] =>
[background_image] =>
[background_color] =>
[text_color] =>
[text_hover_color] =>
[transparent_text_color] =>
[transparent_text_hover_color] =>
[test_select] =>
[test_textarea] =>
[test_pages_dropdown] =>
[icon_number] => 0
)
)
)
现在我试着这样做:
$my_obj[0]
我得到了
注意未定义的偏移量0 ......
我无法从中得到任何东西。但是当我对它做一个foreach时,我可以很好地访问我的对象及其所有属性。
为什么会这样?
答案 0 :(得分:1)
json_decode
将json转换为数组,因此需要显式定义数组。 对于获取stdclass对象,您可以在$object->key
的情况下通过$my_obj[0]->settings
提取数据,或者可以将对象从以下代码转换为数组
foreach ($object as $value)
$array[] = $value->post_id;
答案 1 :(得分:0)
function objectToArray( $object ) {
if( !is_object( $object ) && !is_array( $object ) ) {
return $object;
}
if( is_object( $object ) ) {
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}
尝试此功能(对于多维obj)...并在此处粘贴print_r