简体   繁体   English

如何在PHP中循环遍历多个数组的数组

[英]How to loop through array of multiple arrays in php

I am trying to loop through array of arrays in php. 我正在尝试遍历php中的数组数组。 Usually get stalked with complex array sometimes but I need your kind assistance with this. 通常有时会遇到复杂的数组,但是我需要您的帮助。

var_dump($array) produced the array below: var_dump($array)产生以下数组:

    $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: 使用循环来构建2个单独的数组:

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. 如果任何子数组在2处包含索引,则此方法将不起作用,因此,这明确适用于您提供的示例结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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