如何在for循环中连接对象

时间:2014-09-29 07:46:05

标签: php arrays

我遇到了问题

if (is_array($item)) {
        for ($i=0; $i < count($item['quantity']); $i++) {
            $object->setCurrency($currency);
            $object->setName($item['title'][$i]);
            $object->setQuantity($item['quantity'][$i]);
            $object->setPrice($item['price'][$i]);
            $arr[$i] = (array) $object;
        }
  d($arr);
 }

当我执行var_dump时,结果如下:

Array(
[0] => Array
    (
        [PayPal\Common\PPModel_propMap] => Array
            (
                [currency] => USD
                [name] => Bed Bed
                [quantity] => 1
                [price] => 700
            )

    )

[1] => Array
    (
        [PayPal\Common\PPModel_propMap] => Array
            (
                [currency] => USD
                [name] => Bed Bed
                [quantity] => 1
                [price] => 70.78
            )
    )

我在php中尝试了一些属性数组但没有成功,我想结果应该如下所示 我在php中尝试了一些属性数组,但没有成功,我想结果应该如下所示

 Array
    (
    [0] => PayPal\Api\Item Object
        (
            [_propMap:PayPal\Common\PPModel:private] => Array
                (
                    [currency] => USD
                    [name] => Bed Bed
                    [quantity] => 1
                    [price] => 700
                )

        )

[1] => PayPal\Api\Item Object
    (
        [_propMap:PayPal\Common\PPModel:private] => Array
            (
                [currency] => USD
                [name] => Bed Bed
                [quantity] => 1
                [price] => 70.78
            )

    )

你能帮助我吗?

2 个答案:

答案 0 :(得分:0)

类似的东西:

if (is_array($item)) {
    $arr = array();
    $count = count($item['quantity']);
    for ($i=0; $i < $count; $i++) {
        $object = new stdClass();
        $object->setCurrency($currency);
        $object->setName($item['title'][$i]);
        $object->setQuantity($item['quantity'][$i]);
        $object->setPrice($item['price'][$i]);

        $arr[] = $object;
    }

    var_dump($arr);
}

(我添加了一些小改进和初始化)并删除强制转换为数组(array)$object =&gt; $object)。

答案 1 :(得分:0)

@Etienne

此处为用户用例

时的结果
Array
(
[0] => PayPal\Api\Item Object
    (
        [_propMap:PayPal\Common\PPModel:private] => Array
            (
               [currency] => USD
            [name] => Bed Bed
            [quantity] => 1
            [price] => 70.78
            )

    )

[1] => PayPal\Api\Item Object
    (
        [_propMap:PayPal\Common\PPModel:private] => Array
            (
                [currency] => USD
            [name] => Bed Bed
            [quantity] => 1
            [price] => 70.78
            )

    )