首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将stdClass对象转换为数组

将stdClass对象转换为数组
EN

Stack Overflow用户
提问于 2013-10-21 20:52:28
回答 9查看 339.4K关注 0票数 129

我从postmeta中获取post_id为:

$post_id = $wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE (meta_key = 'mfn-post-link1' AND meta_value = '". $from ."')");

当我尝试print_r($post_id);时,我得到的数组如下:

Array
(
    [0] => stdClass Object
        (
            [post_id] => 140
        )

    [1] => stdClass Object
        (
            [post_id] => 141
        )

    [2] => stdClass Object
        (
            [post_id] => 142
        )

)

我不知道如何遍历它,怎么才能得到这样的数组呢?

Array
(
    [0]  => 140


    [1] => 141


    [2] => 142

)

你知道我该怎么做吗?

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2013-10-21 20:55:35

最简单的方法是对对象进行JSON编码,然后将其解码为数组:

$array = json_decode(json_encode($object), true);

或者,如果您愿意,也可以手动遍历对象:

foreach ($object as $value) 
    $array[] = $value->post_id;
票数 297
EN

Stack Overflow用户

发布于 2014-06-20 02:13:07

非常简单,首先将您的对象转换为json对象,这将把您的对象的字符串返回到JSON表示。

获取结果并使用额外参数true进行解码,其中它将转换为关联数组

$array = json_decode(json_encode($oObject),true);
票数 65
EN

Stack Overflow用户

发布于 2013-10-21 20:54:30

试试这个:

$new_array = objectToArray($yourObject);

function objectToArray($d) 
{
    if (is_object($d)) {
        // Gets the properties of the given object
        // with get_object_vars function
        $d = get_object_vars($d);
    }

    if (is_array($d)) {
        /*
        * Return array converted to object
        * Using __FUNCTION__ (Magic constant)
        * for recursive call
        */
        return array_map(__FUNCTION__, $d);
    } else {
        // Return array
        return $d;
    }
}
票数 24
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19495068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档