1

If i hand code each array value like this:

$paymentDetailsType->setPaymentDetailsItem(
    array (
        'PaymentDetailsItem00' => $paymentDetailsItem,
        'PaymentDetailsItem01' => $paymentDetailsItem1,
    )
);

it works, however the number of array items can vary so i tried this with horrible results not sure what else to try

for ($i=0; $i<$_POST['cartcount']; $i++) {
    if ($i==0) {
        $paymentDetailsType->setPaymentDetailsItem(
            array (                     
                'PaymentDetailsItem00' => $paymentDetailsItem,
            )
        );
    } else {
        $paymentDetailsType =& $paymentDetailsType->setPaymentDetailsItem(
            array (
                'PaymentDetailsItem0'.$i.'' => ${'paymentDetailsItem'.$i},
            )
        );
    }
}

What I believe I am trying to do is add an array value to an object method.

2
  • 1
    Can you create an array first, and then pass that array as a parameter to your method? Commented Jun 20, 2012 at 21:45
  • @robonerd what a simple solution! yes that did the trick just created an array then add keys and values with a for loop then added the object property as the full array Commented Jun 20, 2012 at 22:04

2 Answers 2

2
$thenewarray = array (
    'PaymentDetailsItem00' => $paymentDetailsItem,
);

if ($_POST['cartcount']>1) {
    for ($i=1; $i<$_POST['cartcount']; $i++) {
        $thenewarray['PaymentDetailsItem0'.$i.''] = ${'paymentDetailsItem'.$i};
    }
    $i=0;
}

$paymentDetailsType->setPaymentDetailsItem($thenewarray);

created the array beforehand then loop through added the keys and values finally after the array has been completed add it to the object

Sign up to request clarification or add additional context in comments.

Comments

0
$paymentDetailsType =& $paymentDetailsType->setPaymentDetailsItem(
            array (
                'PaymentDetailsItem0'.$i.'' => ${'paymentDetailsItem'.$i},
            )
        );

This part won't work, because you can't expect two objects to be merged when using =&. When you want to add arrays, you can call array_merge(). You could for example change your paymentDetailsType to this:

class paymentDetailsType
{
    private $_items = array();

    function addPaymentDetailsItem($items)
    {
        $_items = array_merge($_items, $items);
    }
}

Besides that, when you change ${'paymentDetailsItem'.$i} to being an array, you can simply address the items as $paymentDetailsItem[$i] and simply use $i as the key.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.