在PHP中将stdClass对象转换为数组

154

我从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

)

你有什么想法可以帮我完成这个吗?

14个回答

343

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

$array = json_decode(json_encode($object), true);
或者,如果您愿意,也可以手动遍历对象:
foreach ($object as $value) 
    $array[] = $value->post_id;

3
为什么我们不能只使用 $array = json_decode($object, true) - akshaynagpal
4
如果你给一个期望接收JSON字符串作为输入的函数一个对象,它会导致错误。在这个答案中,我将对象转换为JSON字符串,然后将其作为输入提供给json_decode()函数,以便它返回一个数组(第二个参数设置为True表示应该返回一个数组)。 - Amal Murali
7
我知道现在已经太晚了,但为什么你不使用类型转换... (数组) $obj - chhameed
1
@NgSekLong:不是很,不。 - Amal Murali
2
@chhameed:如果您的对象内嵌其他对象,则类型转换将无效。请参见示例-https://eval.in/1124950 - Amal Murali
显示剩余6条评论

68

非常简单,首先将您的对象转换为JSON对象,这将返回一个字符串,代表您的对象。

使用额外的参数true对该结果进行解码,它将被转换为关联数组。

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

1
问题在于值不是可JSON编码的或者不标准化,例如日期。 - Kangur

28

试试这个:

$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;
    }
}

1
将stdobject转换为数组的完美函数 - Vivek

23

您可以像这样将std对象转换为数组:

$objectToArray = (array)$object;

4
这很棒,但它只转换第一层。如果你有嵌套,你必须对所有节点进行操作。 - Ivan Carosati

22

将 stdClass Object 转换为数组有两种简单的方法

$array = get_object_vars($obj);

而另一个是

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

或者你可以使用foreach循环来创建数组

$array = array();
foreach($obj as $key){
    $array[] = $key;
}
print_r($array);

7

对于一维数组:

$array = (array)$class; 

对于多维数组:

function stdToArray($obj){
  $reaged = (array)$obj;
  foreach($reaged as $key => &$field){
    if(is_object($field))$field = stdToArray($field);
  }
  return $reaged;
}

5
欢迎来到SO。您介意详细解释一下您的回答如何解决问题吗? - gung - Reinstate Monica
对于一维数组:$array = (array)$class;对于多维数组:与上述代码相同 - Stack Overflow

6
在将 STD 类对象转换为数组时,可以使用 PHP 的array函数将对象转换为数组。请尝试以下代码片段。
/*** cast the object ***/    
foreach($stdArray as $key => $value)
{
    $stdArray[$key] = (array) $value;
}   
/*** show the results ***/  
print_r( $stdArray );

这将把外部对象转换为数组,但如果任何属性也是对象,则不会被转换。 - Coleman
根据OP的问题,他有一个对象结构的层级。对于下一级,您需要添加另一个foreach循环。 - Nagama Inamdar

5
$wpdb->get_results("SELECT ...", ARRAY_A);

ARRAY_A是一个“output_type”参数。它可以是四个预定义常量之一(默认为OBJECT):

OBJECT - result will be output as a numerically indexed array of row objects.
OBJECT_K - result will be output as an associative array of row objects, using first columns values as keys (duplicates will be discarded).
ARRAY_A - result will be output as an numerically indexed array of associative arrays, using column names as keys.
ARRAY_N - result will be output as a numerically indexed array of numerically indexed arrays.  

请看:

参考:http://codex.wordpress.org/Class_Reference/wpdb


1
这是WordPress世界中唯一建议的方法。 - Raptor

3
您可以尝试这样做:
$aInitialArray = array_map(function($oObject){
    $aConverted = get_object_vars($oObject);
    return $aConverted['post_id'];
}, $aInitialArray);

2

如果你有一个数组,其中的元素是stdClass项,那么这就是解决方案:

foreach($post_id as $key=>$item){
    $post_id[$key] = (array)$item;
}

现在stdClass已被替换为数组,作为新的数组元素。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接