Oyedele Femi
Oyedele Femi

Reputation: 167

How to loop through array of multiple arrays in php

I am trying to loop through array of arrays in php. Usually get stalked with complex array sometimes but I need your kind assistance with this.

var_dump($array) produced the array below:

    $arrayVal = array(6) {
      ["item_id"]=>
      array(2) {
        [0]=>
        string(1) "1"
        [1]=>
        string(1) "2"
      }
      ["request_explanation"]=>
      array(2) {
        [0]=>
        string(7) "Welcome"
        [1]=>
        string(11) "Hello World"
      }
      ["quantity"]=>
      array(2) {
        [0]=>
        string(1) "4"
        [1]=>
        string(1) "4"
      }
      ["unit_cost"]=>
      array(2) {
        [0]=>
        string(1) "4"
        [1]=>
        string(1) "3"
      }
      ["total_cost"]=>
      array(2) {
        [0]=>
        string(1) "0"
        [1]=>
        string(1) "0"
      }
      ["supporting_document"]=>
      string(0) ""
    }

My database table:

enter image description here

I want to be able to save each of the value in that array into the table above. Thanks for helping me.

Upvotes: 0

Views: 393

Answers (2)

Kisaragi
Kisaragi

Reputation: 2218

Use a loop to build 2 separate arrays:

foreach($array['ExpensesList'] as $index => $val){
    $array1[$index] = $array['ExpensesList'][$index][0];
    $array2[$index] = $array['ExpensesList'][$index][1];
}

Then insert each array into your database individually.

This will not work if any sub array contains an index at 2, so this is explicitly for the example structure you provided.

Upvotes: 0

Barmar
Barmar

Reputation: 780724

Use the indexes of one of the sub-arrays to access all the other sub-arrays:

foreach ($array['item_id'] as $i => $item_id) {
    $request_explanation = $array['request_explanation'][$i];
    $quantity = $array['quantity'][$i];
    // repeat this for all the columns
    // Now you can insert all these variables into the database
}

Upvotes: 1

Related Questions