Home > database >  How To Insert Data Array to different table when he result is offset?
How To Insert Data Array to different table when he result is offset?

Time:03-18

I have data as below:

Array
          (
              'action' => 'Buy',
              'barcode' => '8993200661336',
              'price' => 9000,
              'intCode' => '30209423',
              'quantity' => 1,
              'promoDiscount' => Array
                  (
                      0 => Array
                          (
                              'promoId' => 'P00722000091',
                              'percentage' => 10,
                              'amount' => 900,
                          ),

                          1 => Array
                          (
                              'promoId' => 'P00221000044',
                              'percentage' => 10,
                              'amount' => 900,
                          ),
                        ),
);

In Array promoDiscount value insert to different table, into 2 rows of data. if I insert intCode into the table, the value only goes to array index [0], while for array index[1] the result is offset.

how to insert intCode into index array[0] & index array[1] ?

CodePudding user response:

If I understood correctly, you simply want to move the same intCode value inside the sub-arrays of promoDiscount.

You just need to add the additional parameter, looping either with for or foreach to make it dynamic. Like this:

<?php

foreach ($array['promoDiscount'] as $key => $val) {
    $array['promoDiscount'][$key]['intCode'] = $array['intCode'];
}
?>

This will change your array to

  ["action"]=>
  string(3) "Buy"
  ["barcode"]=>
  string(13) "8993200661336"
  ["price"]=>
  int(9000)
  ["intCode"]=>
  string(8) "30209423"
  ["quantity"]=>
  int(1)
  ["promoDiscount"]=>
  array(2) {
    [0]=>
    array(4) {
      ["promoId"]=>
      string(12) "P00722000091"
      ["percentage"]=>
      int(10)
      ["amount"]=>
      int(900)
      ["intCode"]=>
      string(8) "30209423"
    }
    [1]=>
    array(4) {
      ["promoId"]=>
      string(12) "P00221000044"
      ["percentage"]=>
      int(10)
      ["amount"]=>
      int(900)
      ["intCode"]=>
      string(8) "30209423"
    }
  }
}

CodePudding user response:

Let's call your array $array

$array['promoDiscount'] [0] ['intCode'] = 'yourValue' 
$array['promoDiscount'] [1] ['intCode'] = 'yourValue'

Or you can use for loop for $array['promoDiscount']

  • Related