如何使用merge字段和changename属性创建一个新的php数组



我尝试在laravel中更改php中的数组。我有一个带有重复字段的嵌套数组。但是有一个i要更改名称时间戳。我该怎么做?

$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,
),
);

我想做这样的东西:

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,
),

提前感谢!

我不确定"分组键"是设备、值还是两者都是,但无论如何。我会使用for循环来绘制它,然后从地图上删除密钥:

$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;
}

如果你知道每个键总是有偶数个事件,并且每个键可能有两个以上的事件,你可以合并两个foreach,这样当你添加"结束"时间戳时,你也可以将元素添加到$return中,并将元素从映射中删除(允许它在出现时再次插入(。

$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"],
];
}
}

首先,尝试使用基于设备名称的分组数组,您可以使用此页面进行示例算法:url

然后使用foreach循环,您可以获得设备名称的每个时间戳,并可以将设备添加到一个数组中,如下所示:

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

最新更新