I try to implement my HmIP devices and I'm using a python script to retrieve my values. I get an array, which I exploded with a foreach:
foreach ($output as $line) {
$raw = explode (" ", $line);
$device[$raw['2']] = $raw;
}
Now my array looks like this:
[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)
Now I want to create a 'beautified' array like:
[Outdoor] => Array
(
[device_id] => 1234ABDCFGD
[device_type] => HmIP-STHO
[lowbat] => false
[unreach] => false
...
As you can see key 1-2 is static, the rest dynamic and it differs per device type. I don't know where to start, any help is appreciated.
CodePudding user response:
You can use the array_combine function to build an array from two, the first containing the keys, the second holding the values.
<?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);
CodePudding user response:
With the help of @Pinke Helga I was able to write the following working script:
$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);
}
Is there a better way to achieve this?