Home > Software engineering >  how to make a new php array with merge fields and change name attributes
how to make a new php array with merge fields and change name attributes

Time:08-06

i am try change a array in php in laravel. i have a nested array with duplicate fields. but there is one i what to change the name timestamp. how can i do this?

    $consumos = array(
    array(
        "device" => "EA1",
        "timestamp" => "2020-01-01 21:00:00",
        "value" => 4,

    ),
    array(
        "device" => "EA1",
        "timestamp" => "2020-01-01 07:00:00",
        "value" => 4,

    ),
    array(
        "device" => "EA2",
        "timestamp" => "2022-01-01 12:00:00",
        "value" => 2,

    ),
    array(
        "device" => "EA2",
        "timestamp" => "2022-01-01 13:00:00",
        "value" => 2,

    ),

);

i what to make something like this:

array(
        "device" => "EA1",
        "start" => "2020-01-01 21:00:00",
        "end" => "2020-01-01 07:00:00",
        "value" => 4,
    ),
array(
        "device" => "EA1",
        "start" => "2022-01-01 12:00:00",
        "end" => "2022-01-01 13:00:00",
        "value" => 2,
    ),

thanks in advance!

CodePudding user response:

I'm not sure if the 'grouping key' is the device, the value, or both, but anyway. I'd use a for-loop to map it, then drop the keys from the map:

$map = [];
foreach ($consumos as $consumo) {
    $key = $consumo["device"]; // or value, or both
    if (isset($map[$key])) {
        $map[$key]["end"] = $consumo["timestamp"];
    } else {
        $map[$key] = [
            "device" => $consumo["device"],
            "start" => $consumo["timestamp"],
            "value" => $consumo["value"],
        ];
    }
}
$return = [];
foreach ($map as $ret) {
    $return[] = $ret;
}

If you know you'll always have an even number of events per key, and there can be more than two events per key, you could merge both foreach, and make it so when you add an 'end' timestamp, you also add the element to $return and drop the element from the map (allowing it to be inserted again when it shows up).

$map = [];
$return = [];
foreach ($consumos as $consumo) {
    $key = $consumo["device"]; // or value, or both
    if (isset($map[$key])) {
        $map[$key]["end"] = $consumo["timestamp"];
        $return[] = $map[$key];
        unset($map[$key]);
    } else {
        $map[$key] = [
            "device" => $consumo["device"],
            "start" => $consumo["timestamp"],
            "value" => $consumo["value"],
        ];
    }
}

CodePudding user response:

first, try using a grouping array based on the device name, you can use this page for sample algorithm: url

then with a foreach loop, you can get each timestamp of the device name and you can add devices to an array like this :

$newArray[] = [
        // other fields ...
        "start" => $item[0]['timestamp'],
        "end" => $item[1]['timestamp'],
]
  • Related