PHP从对象属性创建一个多维数组

时间:2012-04-04 16:46:08

标签: php arrays object

我的情况非常艰难。

有一些这些对象

ProductionItem Object
(
    [customer] => Customer Object
        (
            [customer_id] =>24
            [company_type] => Limited Company
            [date_created] => 2009-01-28 15:55:50
            [vat] => 
            [status] => 1
            [account_number] => 590893
        )

    [woi_id] => 67017
    [od_id] => 7154
    [pd_id] => 1112
    [od_qty] => 0
    [od_color] => TEAL BLUE
)

我正在尝试将其转换为类似于此结构的多维数组

$allOrders[24] = array (
        objects[0] => array(
                'woid_ud' = 67017,
                'od_id' = 7154,
                'pd_id' = 1112,
                'od_qty' = 0,
                'od_color' = 'TEAL BLUE'
                ),
        objects[1] => array(
                'woid_ud' = 75839,
                'od_id' = 5890,
                'pd_id' = 2344,
                'od_qty' = 0,
                'od_color' = 'TEAL GRAY'
                )
        )

我有什么遗漏,这真的很容易吗?拜托,建议我。我试过迭代这些对象,它仍然不起作用,看起来很难看。

1 个答案:

答案 0 :(得分:1)

您应该使用get_object_vars函数。

function object_to_array($obj){
    if(!is_object($obj)){
       return $obj;
    }
    $data = array();
    foreach(get_object_vars($obj) as $k=>$v){
        $data[$k] = object_to_array($v);
    }
    return $data;
}