嗨我有结构数组,如
array:2 [
0 => array:3 [
"title" => "samba"
"diff" => "06:30:00"
"user" => "Janek"
]
1 => array:3 [
"title" => "Ramba"
"diff" => "03:30:00"
"user" => "Janek"
]
2 => array:3 [
"title" => "fit"
"diff" => "03:30:00"
"user" => "Pawel"
]
]
输出应该是
array:2 [
0 => array:3 [
"title" => "samba"
"sum" => "10"
"user" => "Janek"
]
1 => array:3 [
"title" => "Ramba"
"sum" => "03:30:00"
"user" => "Pawel"
]
]
我需要对所有diff键求和,但对于用户。 例如user => janek sum diff => 10 user => Pawel sum diff =>> 3:30
我试过
$values=array_sum(array_column($newArray,'diff))
但是这个总和所有数组。 我希望你理解。
答案 0 :(得分:0)
我找到了你的答案。那么这里的代码很乱,但我认为你可以自己管理休息......任何编辑建议也欢迎...
<?php
$sumArray = array();
$myArray = array(
0 => array(
"title" => "samba",
"diff" => "06:30:00",
"user" => "Janek"
),
1 => array(
"title" => "Ramba",
"diff" => "03:30:00",
"user" => "Janek",
),
2 => array(
"title" => "fit",
"diff" => "03:30:00",
"user" => "Pawel"
)
);
$i = 0;
$xarray = array();
foreach ($myArray as $k=>$subArray)
{
$parts = explode(':', $subArray["diff"]);
$seconds = ($parts[0] * 60 * 60) + ($parts[1] * 60) + $parts[2];
if(in_array($subArray["user"],$xarray)):
$key = myfunction( $sumArray,"user",$subArray["user"]);
$sumArray[$key]["sum"] = gmdate("H:i:s", $sumArray[$key]["sum1"]+$seconds);
else:
$sumArray[$i] = $subArray;
$sumArray[$i]["sum1"] = $seconds;
$sumArray[$i]["sum"] = gmdate("H:i:s",$seconds);
$xarray[] = $subArray["user"];
$i++;
endif;
}
foreach($sumArray as $key=>$value)
{
unset($sumArray[$key]["diff"]);
unset($sumArray[$key]["sum1"]);
}
function myfunction($arrays, $field, $value)
{
foreach($arrays as $key => $product)
{
if ( $product[$field] === $value )
return $key;
}
}
echo "<pre>";
print_r($sumArray);
echo "</pre>";
输出: -
Array
(
[0] => Array
(
[title] => samba
[user] => Janek
[sum] => 10:00:00
)
[1] => Array
(
[title] => fit
[user] => Pawel
[sum] => 03:30:00
)
)
答案 1 :(得分:0)
要总结分组用户的小时数,请使用DateTime::add()
,preg_replace
和array_values
函数使用以下方法:
// supposing $arr is your initial array
$result = [];
foreach ($arr as $el) {
if (!isset($result[$el['user']])) {
$result[$el['user']] = $el;
} else {
$interval = new \DateInterval(preg_replace("/^(\d{2}):(\d{2}):\d{2}$/", 'PT$1H$2M', $el['diff']));
$result[$el['user']]["diff"] = (new \DateTime($result[$el['user']]["diff"]))->add($interval)->format('H:i:s');
}
}
foreach ($result as &$v) { // renaming keys 'diff'/'sum'
$v["sum"] = $v["diff"];
unset($v["diff"]);
}
print_r(array_values($result));
输出:
Array
(
[0] => Array
(
[title] => samba
[user] => Janek
[sum] => 10:00:00
)
[1] => Array
(
[title] => fit
[user] => Pawel
[sum] => 03:30:00
)
)