2

I have a multi dimensional array that have a structure like this

[nmbr] => Array
       (
           [0] => u
           [1] => t
       )
[jmlh] => Array
        (
           [0] => 4
           [1] => 6
        )

and I want to insert it into a database that will be looked like

id   nmbr   jmlh
1    u      4
2    t      6

i try using a for loop but it only detect the first array, the second one is not inserted into the database.

this is my for looping

$namabarang = $_POST['nmbr'];
$jumlah = $_POST['jmlh'];
for ( $i = 0; $i<$total; $i++)
{
  $nmbr = $namabarang[$i];
  $jmlh = $jumlah[$i];
  $data = array(
    'id_tender' => $primary_key,
        'nmbr' => $nmbr,
        'jumlah' => $jmlh
        );
  $this->db->insert('tb_tender_barang', $data);
}
5
  • 2
    Where are you specifying $total ? Commented Jun 5, 2014 at 2:28
  • I think it's not looping "enough" to insert both of them. Commented Jun 5, 2014 at 2:30
  • add $total = (count($namabarang) > count($jumlah)) ? count($namabarang) : count($jumlah); before the for loop. This is equivalent to saying if $namabarang has more elements then $jumlah then set $total to equal the amount of items in $namabarang else set item count from $jumlah Commented Jun 5, 2014 at 2:36
  • if nmbr and jmlh always have the same number of count. You can just use foreach Commented Jun 5, 2014 at 2:42
  • I forgot to mention > $total=count($namabarang) and yes, nmbr and jmlh always have the same number of count, and how do i use foreach because i tried and still get array not the string inside the array Commented Jun 5, 2014 at 2:55

1 Answer 1

1

If both arrays will have the same size. A simple for loop should suffice. In your current code, you didn't check the size of either of them that you used inside the loop. Consider this example:

// this will just strictly work if they have the same size!
$namabarang = $_POST['nmbr'];
$jumlah = $_POST['jmlh'];

for($i = 0, $size = count($jumlah); $i < $size; $i++) {
    $data = array('id' => $i+1, 'nmbr' => $nmbr[$i], 'jmlh' => $jmlh[$i]);
    $this->db->insert('tb_tender_barang', $data);
}

Sidenote: Why do you need to manually insert the id in the table? Let the AUTO INCREMENT handle that for you.

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

1 Comment

it works perfect! thankyou kevinabelita :) and yes, i auto increment the id, thank you very much once again :)

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.