我有一个类似
的数组array(3) {
[0]=> array(2) {
["AllotmentId"]=> string(36) "6b594c22-73f1-0a2a-298c-2d3feba2905d"
["RoomId"]=> string(36) "9a21e427-16fd-7a9e-bc16-537dc55093bb" }
[1]=> array(2) {
["AllotmentId"]=> string(36) "99730f9a-2242-24bd-0908-b9035a75d328"
["RoomId"]=> string(36) "9a21e427-16fd-7a9e-bc16-537dc55093bb" }
[2]=> array(2) {
["AllotmentId"]=> string(36) "fft54c22-73f1-0a2a-2558c-2d3fgged"
["RoomId"]=> string(36) "663ghjytf-16fd-7a9e-bc16-537dc55r5g0" }
}
现在我想创建另一个数组,它将存储以下信息,如
[
RoomId => "9a21e427-16fd-7a9e-bc16-537dc55093bb", NumberOfAllotments => 2
RoomId => "663ghjytf-16fd-7a9e-bc16-537dc55r5g0", NumberOfAllotments => 1
]
它应该根据房间ID计算分配ID的数量并创建另一个数组。
我无法调整以下代码行。
foreach ($allotmentArray as $key => $allotment)
{
$arrayToPush = array('RoomId' => $allotment["RoomId"], "NumberOfAllotments" => $count]);
array_push($freeRooms, $arrayToPush);
}
请帮助!!!
答案 0 :(得分:1)
试试这段代码:
首先计算并保存在一个名为$ targetArray的键值数组中。 然后在$ outputArray中生成首选输出:
<?php
$targetArray = array();
foreach ($allotmentArray as $allotment)
{
if(!array_key_exists($allotment['RoomId'], $targetArray))
$targetArray[$allotment['RoomId']] = 0;
$targetArray[$allotment['RoomId']]++;
}
$outputArray = array();
foreach($targetArray as $RoomId=> $count)
$outputArray[] = array('RoomId'=>,'count'=>$count);
var_dump($outputArray);
答案 1 :(得分:1)
试试这个:
INSERT INTO [OrdForm].[dbo].[SeasonDepSexGroup]
(Code, Sex10Code, DepartmentCode, LastModified, SeasonCode, KlasseCode, CompanyCode, Kenmerk2)
SELECT Code, Sex10Code, DepartmentCode, LastModified, 91, KlasseCode, CompanyCode, Kenmerk2
FROM [SeasonDepSexGroup]
WHERE DepartmentCode = 'UD' and KlasseCode = 'U'
1 /我创建一个临时数组
// Your array
$array = array(
0 => array(
"AllotmentId" => "6b594c22-73f1-0a2a-298c-2d3feba2905d",
"RoomId" => "9a21e427-16fd-7a9e-bc16-537dc55093bb" ),
1=> array(
"AllotmentId"=> "99730f9a-2242-24bd-0908-b9035a75d328",
"RoomId" => "9a21e427-16fd-7a9e-bc16-537dc55093bb" ),
2=> array(
"AllotmentId"=> "fft54c22-73f1-0a2a-2558c-2d3fgged",
"RoomId"=> "663ghjytf-16fd-7a9e-bc16-537dc55r5g0" )
);
2 /然后我在此临时数组中添加所有roomId值
$temp_array = array();
3 /现在我计算每个房间的数量
foreach ($array as $key => $data) {
$temp_array[] = $data['RoomId'];
}
这里的输出是:
$temp_result = array_count_values($temp_array);
4 /现在我将构建我的结果数组
array (size=2)
'9a21e427-16fd-7a9e-bc16-537dc55093bb' => int 2
'663ghjytf-16fd-7a9e-bc16-537dc55r5g0' => int 1
5 /我添加了一个带有roomId和分配数量的新数组
$result = array();
这是输出:
foreach ($temp_result as $roomId => $NumberOfAllotments) {
$result[] = array(
'RoomId' => $roomId,
'NumberOfAllotments' => $NumberOfAllotments
);
}
这是你在找什么?
我认为你可以通过一些php数组函数找到另一种方法,但这种方法有效(如果我理解你想要的话!)
答案 2 :(得分:1)
我认为你不需要循环 使用array_column和array_count_values。
$Roomid = array_count_values(array_column($arr, "RoomId"));
现在Roomid键是Roomid,值是每个的计数。
如果你的问题中必须有数组,你可以这样做:
$Roomid = array_count_values(array_column($arr, "RoomId"));
Foreach($Roomid as $room => $count){
$arr[] = ["Roomid" => $room, 'NumberOfAllotments' => $count];
}
这只会循环每个独特的房间,而不是整个阵列。
输出(一个或多个):
https://3v4l.org/ohUJS