0

I have the following cart implemented by a custom module I wrote.

screenshot

The columns are stored in 2 associative arrays.

$jcartItemQty = $_POST['jcartItemQty'];
$jcartItemPrice = $_POST['jcartItemPrice'];

This is what those array could contain:

     [jcartItemQty] => Array
            (
                [0] => 3
                [1] => 1
            )

        [jcartItemName] => Array
            (
                [0] => Armas Jarnefelt - LAULAJAN KOTI
                [1] => Jean Sibelius - Kullervo
            )

        [jcartItemPrice] => Array
            (
                [0] => 110
                [1] => 120
            )

I need to combine somehow the arrays into one that looks like $combined = (3 => 110, 1 => 120) in order to be able to calculate the total. array_merge() is not working because will only concatenate those 2 arrays.

foreach ($combined as $key => $item) {
  $total += $key * $item;
}

I need to display the total in a form item like this:

foreach ($jcartItemPrice as $key => $value) { 
  $form['jcartItemPrice'][$key] = array(
    '#type' => 'textfield',
    '#value' => isset($value) ? $value : '',
  );
}

$form['total'][$key] = array(
  '#type' => 'textfield',
  '#value' => isset($value) ? $value : '',
);

Is there a way to do this?

1

Assuming the array keys of each array will always match (and that is what you're using to tie the two arrays together):

$total = 0;
foreach ($jcartItemPrice as $key => $price) {
  $total += $price * $jcartItemQty[$key];
}
1

You can use array_merge() to merge two arrays into one.

It looks like you're trying to overengineer things. This is a simple solution:

$combined = array();
for ($i = 0; $i < count($jcartItemQty); $i++) {
  $combined[] = array($jcartItemQty[$i], $jcartItemPrice[$i]);
}
  • Thank you Florian, nice way to pair 2 matrices. I will keep in my code snippets. Clive has a nice solution to calculate without pair it so I think we both overengineered it :) - it was my idea to pair up things :)) – drupal_stuff_alter Feb 29 '12 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.