繁体   English   中英

使用 PHP - 添加额外的子阵列

[英]Using PHP - Add an additional subarray

我有两个 arrays。 第一个阵列由具有不同细节的不同子阵列的设备组成。 第二个数组有 1 行或更多行项目详细信息。 arrays 都有一个共同的“hostid”字段。 如何获取第一个数组并添加一个名为 items 的新子数组和 append 数组 2 中“hostid”匹配的所有行?

阵列 1

0:
host: "4303-CAM-01.1"
hostid: "11367"
interfaces: (2) [{…}, {…}]
inventory: {vendor: "AXIS", model: "M5525-E", serialno_a: "1234567890", host_networks: "192.168.1.100", macaddress_a: "XX:XX:XX:XX:XX", …}
tags: (2) [{…}, {…}]

阵列 2

0: {itemid: "263571", hostid: "11367", key_: "icmpping[{$CAMIP}]", lastvalue: "1"}
1: {itemid: "263572", hostid: "11367", key_: "icmppingloss[{$CAMIP}]", lastvalue: "0"}
2: {itemid: "263573", hostid: "11367", key_: "icmppingsec[{$CAMIP}]", lastvalue: "0.0009"}
3: {itemid: "263593", hostid: "11368", key_: "icmpping[{$CAMIP}]", lastvalue: "1"}
4: {itemid: "263594", hostid: "11368", key_: "icmppingloss[{$CAMIP}]", lastvalue: "0"}
5: {itemid: "263595", hostid: "11368", key_: "icmppingsec[{$CAMIP}]", lastvalue: "0.0010"}

期望的结果

0:
host: "4303-CAM-01.1"
hostid: "11367"
interfaces: (2) [{…}, {…}]
inventory: {vendor: "AXIS", model: "M5525-E", serialno_a: "1234567890", host_networks: "192.168.1.100", macaddress_a: "XX:XX:XX:XX:XX", …}
tags: (2) [{…}, {…}]
items Array(3):
0: {itemid: "263571", key_: "icmpping[{$CAMIP}]", lastvalue: "1"}
1: {itemid: "263572", key_: "icmppingloss[{$CAMIP}]", lastvalue: "0"}
2: {itemid: "263573", key_: "icmppingsec[{$CAMIP}]", lastvalue: "0.0009"}
$array1 = subarrays;
$array2 = itemdetails;

$array1['item'] = $array2;

只需在第一个中创建一个数组值,它等于数组 2。

您必须遍历第一个数组,然后检查第二个数组中的每个项目:

foreach($array1 as &$host) { // set the host as reference
    $items = []; // create a new array to store the items
    foreach($array2 as $item) {
        if ($item->hostid === $host->hostid) {
            $items[] = $item; // push the item to the empty array
        }
    }
    $host->items = $items; // update the items to the host
}

希望这可以帮助。

暂无
暂无

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

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