如何创建一个看起来像这样的数组?

时间:2013-07-05 14:51:44

标签: php arrays stdclass

我有一个数组。 print_r的结果这个数组是这样的:

Array
(
    [flat_rate] => WC_Shipping_Rate Object
        (
            [id] => flat_rate
            [label] => book
            [cost] => 8000
            [taxes] => Array
                (
                )

            [method_id] => flat_rate
        )

    [local_delivery] => WC_Shipping_Rate Object
        (
            [id] => local_delivery
            [label] => dvd
            [cost] => 15000
            [taxes] => Array
                (
                )

            [method_id] => local_delivery
        )

)

我需要像这样创建数组。 我通过这段代码尝试这个数组:

Array("flat_rate" => (object) Array("id" => "flat_rate" ,"label" => "book" ,"cost" => 8000 ,"taxes" => Array ( ) ,"method_id" => "flat_rate") ,"local_delivery" => (object) Array("id" => "local_delivery" ,"label" => "book" ,"cost" => 15000 ,"taxes" => Array ( ) ,"method_id" => "local_delivery"));

但是当print_r这个数组 WC_Shipping_Rate 改变 stdClass

1 个答案:

答案 0 :(得分:2)

很难理解,你真正想做什么。据我了解你,你想在一个数组中包含实例WC_Shipping_Rate的对象吗?如果是这样,你必须创建一个WC_Shipping_Rate类的新实例$object = new WC_Shipping_Rate;然后,你可以填充它并应用于你的数组:

$object = new WC_Shipping_Rate();
$object->id = 'local_delivery'; // OR with setter, if the class has it $object->setId('local_delivery');
$object->label = 'dvd';
// ...etc
$array = array(
    "flat_rate" => $object
);