如何合并两个数组?

时间:2019-01-08 10:12:50

标签: php

进行循环后并使用以下数组,我可以创建一个新数组。

$data[$val['gid']][$val['rid']][$val['aid']][$teno][$userid]= array();

这将导致以下数组:

array:1 [
  "FS OTHER" => array:1 [
    "FS OTHER" => array:1 [
      "FS OTHER" => array:1 [
        "FS OTHER" => array:1 [
          "D111" => []
        ]
      ]
    ]
  ]
]

我还有另一个数组:

array:41 [
  0 => array:2 [
    "sid" => "D111"
    "desc1" => "BANGKOK"
  ]
  1 => array:2 [
    "sid" => "D111"
    "desc1" => "NONTHABURI"
  ]
  2 => array:2 [
    "sid" => "D112"
    "desc1" => "PATHUM THANI"
  ]

现在我需要基于'sid'合并此数组以获得以下结果:

array:1 [
  "FS OTHER" => array:1 [
    "FS OTHER" => array:1 [
      "FS OTHER" => array:1 [
        "FS OTHER" => array:1 [
          "BANGKOK" => []
          "NONTHABURI"=> []
        ]
      ]
    ]
  ]
]

1 个答案:

答案 0 :(得分:2)

您可以准备第二个数组的另一种结构

$new = [];
foreach ($arr2 as $x) {
    $new[$x['sid']][$x['desc1']] = [];
}
// [D111 => [ BANGKOK => [], NONTHABURI => [] ],..

然后通过以下方式创建第一个:

$data[$val['gid']][$val['rid']][$val['aid']][$teno][$userid]= $new[$userid];