0

I have an array loop 1st value in array is name and second value is the value to be inserted in the combination of 2 the array printing like this

Array
(
[0] => LE781291334
[1] => 0
[2] => JR792682920
[3] => 8,000.00
[4] => JR792733067
[5] => 1,800.00
[6] => JR792733072
[7] => 1,500.00
[8] => JR792733069
[9] => 700
[10] => JR792733068
 )

Which I need every array values to be paired so I can add them into database like this

INSERT INTO table_name (valname, value) VALUES ('LE781291334', 0)
INSERT INTO table_name (valname, value) VALUES ('JR792682920', 8,000.00)
INSERT INTO table_name (valname, value) VALUES ('JR792733067', 1,800.00)

I am totally confused the value coming through api and I cannot pair them can anyone help me out for adding them in paired way?

Mark Alan
  • 13
  • 4
  • 1
    Possible duplicate of [Reorganizing an array: odd entries as KEY, even entries as VALUE](https://stackoverflow.com/questions/8501422/reorganizing-an-array-odd-entries-as-key-even-entries-as-value) - Agreed, bad format for the API to return. – ficuscr May 23 '19 at 17:49

2 Answers2

3

It seems you need to array_chunk the array.
The function array_chunk will chunk up an array in x parts with $n number of items in each.

$n = 2;
$result = array_chunk($yourarray, $n);

Use it then like:

foreach($result as $sub){
    list($valname, $val) = $sub;
    // Your table code
}
Andreas
  • 23,610
  • 6
  • 30
  • 62
  • awesome that worked for me you are a good responded everyone provided me with duplication which is not even what I was looking for – Mark Alan May 24 '19 at 13:19
  • But I am confused still using array_chunk is it possible to add paired values in sql query is i HAVE TO ADD LIKE THIS INSERT INTO table_name (valname, value) VALUES ('LE781291334', 0) – Mark Alan May 24 '19 at 13:20
0
$newarray = array();

for ($i = 0; $i < count($yourarray) / 2; $i++) {
    $newarray[$yourarray[$i*2]] = $yourarray[$i * 2 + 1];
}

This assumes $yourarray is an indexed array with an even number of elements, so each key is paired to the succeeding value.

array_chunk as in the previous answer seems to accomplish the same thing, this is just a simple loop to show how it might work.

You could then insert into database with something like this:

foreach ($newarray as $x => $x_value) {
    // sql to insert here - $x is the key and $x_value is the value
}
siralexsir88
  • 418
  • 1
  • 4
  • 14