PHP -重命名数组键-静态和动态混合

7gcisfzg  于 2023-01-08  发布在  PHP
关注(0)|答案(2)|浏览(116)

我试着实现我的HmIP设备,我使用一个python脚本来检索我的值,我得到了一个数组,我用foreach分解了它:

foreach ($output as $line) {
    $raw = explode (" ", $line);
    $device[$raw['2']] = $raw;       
}

现在我的数组如下所示:

[Window-Kitchen] => Array
        (
            [0] => ABCD123EFG
            [1] => HMIP-SWDO
            [2] => Window-Kitchen]
            [3] => lowBat(False)
            [4] => unreach(False)
            [5] => rssiDeviceValue(-75)
            [6] => rssiPeerValue(None)
            [7] => configPending(False)
            [8] => dutyCycle(False)
            [9] => sabotage(False)
            [10] => windowState(CLOSED)
        )

    [Outdoor] => Array
        (
            [0] => 1234ABDCFGD
            [1] => HmIP-STHO
            [2] => Outdoor
            [3] => lowBat(False)
            [4] => unreach(False)
            [5] => rssiDeviceValue(-72)
            [6] => rssiPeerValue(None)
            [7] => configPending(False)
            [8] => dutyCycle(False)
            [9] => temperatureOutOfRange(False)
            [10] => actualTemperature(10.4)
            [11] => humidity(86)
            [12] => vaporAmount(8.275512614884711)

现在我想创建一个“美化”数组,如下所示:

[Outdoor] => Array
        (
            [device_id] => 1234ABDCFGD
            [device_type] => HmIP-STHO
            [lowbat] => false
            [unreach] => false
            ...

正如你所看到的,键1-2是静态的,其余的是动态的,它根据设备类型而不同。我不知道从哪里开始,任何帮助都是感激的。

rta7y2nd

rta7y2nd1#

可以使用array_combine函数从两个数组中构建一个数组,第一个包含键,第二个保存值。

<?php declare(strict_types = 1);

$arr =
[
  'Window-Kitchen' =>  [ 'one', 'two', 'three' ],
  'Outdoor'        =>  [ 'A', 'B'],
];

$keys =
[
  'Window-Kitchen' =>  [ 'key 1', 'key 2', 'key 3' ],
  'Outdoor'        =>  [ 'key A', 'key B'],
];

// alter in place by using a reference &$val
foreach ($arr as $key => &$val)
  $val = array_combine($keys[$key], $val);
cfh9epnr

cfh9epnr2#

在@Pinke Helga的帮助下,我能够写出下面的工作脚本:

$arr_keys = array();
$arr_values = array();
$devices = array();

foreach ($output as $line) {
    $raw = explode (" ", $line);
    
    $foreach_keys = array();
    $foreach_values = array();

    for($i=0; $i < count($raw); $i++) {
        if ($i == 0){
            $foreach_keys[] = 'Device_ID';
            $foreach_values[] = $raw[$i];
        }elseif($i == 1){
            $foreach_keys[] = 'Device_type';
            $foreach_values[] = $raw[$i];
        }elseif($i == 2){
            $foreach_keys[] = 'Device_name';
            $foreach_values[] = $raw[$i];
        }else{
            $foreach_keys[] = strtok($raw[$i], '(');

            preg_match('#\((.*?)\)#', $raw[$i], $match);
            $foreach_values[] = $match[1];
        }
    }

    $arr_keys[] = $foreach_keys;
    $arr_values[] = $foreach_values;
}

foreach ($arr_values as $key => &$val){
    $devices[] = array_combine($arr_keys[$key], $val);
}

有没有更好的方法来实现这一目标?

相关问题