繁体   English   中英

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

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

我正在尝试遍历php中的数组数组。 通常有时会遇到复杂的数组,但是我需要您的帮助。

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) ""
    }

我的数据库表:

在此处输入图片说明

我希望能够将该数组中的每个值保存到上表中。 谢谢你帮我

使用子数组之一的索引来访问所有其他子数组:

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
}

使用循环来构建2个单独的数组:

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

然后将每个数组分别插入数据库。

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

暂无
暂无

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

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