简体   繁体   中英

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:

在此处输入图片说明

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

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM