在PHP中合并多维数组

时间:2019-06-28 15:10:58

标签: php multidimensional-array merge

我有以下2个数组(Array-1,Array-2),并且我想根据以下条件合并为以下单个数组(New-Array)

条件:(如果Array-1(hID)= Array-2(hID),则如下所示)

Array-1

Array
(
    [0] => Array
        (
            [hID] => 107
            [env] => DEV
            [serv] => server1
        )

    [1] => Array
        (
            [hID] => 122
            [env] => DEV
            [serv] => server2
        )

Array-2

Array
(
    [107] => Array
        (
            [hID] => 107
            [cpu] => 32
            [mem] => 24
        )

    [122] => Array
        (
            [hID] => 122
            [cpu] => 16
            [mem] => 24
        )

新数组

Array
(
    [0] => Array
        (
            [hID] => 107
            [env] => DEV
            [serv] => server1
            [cpu] => 32
            [mem] => 24
        )

    [1] => Array
        (
            [hID] => 122
            [env] => DEV
            [serv] => server2
            [cpu] => 16
            [mem] => 24
        )

3 个答案:

答案 0 :(得分:0)

如果第二个数组始终具有与hID值相同的键,则可以执行以下操作:

$newArray = [];
foreach ($array1 as $item) {
    if (isset($array2[$item['hID']])) {
        $newArray[] = array_merge($item, $array2[$item['hID']]);
    }
}

或者您始终可以使用以下方式创建此类数组(键与hID值相同):

$array2 = array_combine(
    array_column($array2, 'hID'),
    $array2
);

答案 1 :(得分:0)

您可以尝试以下方法:

测试数组

$array_1 = [
    0 => [
        "hID" => 107,
        "env" => "DEV",
        "serv" => "server1"
    ],
    1 => [
        "hID" => 122,
        "env" => "DEV",
        "serv" => "server2"
    ] 
];

$array_2 = [
    0 => [
        "hID" => 107,
        "cpu" => 32,
        "mem" => 24
    ],
    1 => [
        "hID" => 122,
        "cpu" => 16,
        "mem" => 24
    ] 
];

合并两个数组的代码

$new_array = [];
 for($i=0;$i<count($array_1);$i++) {
    for($j=0;$j<count($array_2);$j++) {
        if ($array_1[$i]['hID'] === $array_2[$j]['hID']) {
            $new_array[] = array_merge($array_1[$i], $array_2[$j]);
        }
    }
 }

输出:

 var_dump($new_array);

array(2) {
  [0]=>
  array(5) {
    ["hID"]=>
    int(107)
    ["env"]=>
    string(3) "DEV"
    ["serv"]=>
    string(7) "server1"
    ["cpu"]=>
    int(32)
    ["mem"]=>
    int(24)
  }
  [1]=>
  array(5) {
    ["hID"]=>
    int(122)
    ["env"]=>
    string(3) "DEV"
    ["serv"]=>
    string(7) "server2"
    ["cpu"]=>
    int(16)
    ["mem"]=>
    int(24)
  }
}

在这里测试:http://sandbox.onlinephpfunctions.com/

答案 2 :(得分:-1)

 img[(img[:,:,0]< TRESHOLD) and (img[:,:,2]< TRESHOLD)] = 0` (not working) 

$ Array3 = array_merge($ array1,$ array2); }