[英]add to multidimensional array with key value pair
Im returning a array that resembles this idea 我正在返回类似于这个想法的数组
Array
(
[0] => Array
(
[GRP] => "Group1"
[ITM] => "Item1"
)
[1] => Array
(
[GRP] => "Group1"
[ITM] => "Item2"
)
[2] => Array
(
[GRP] => "Group1"
[ITM] => "Item1"
)
[3] => Array
(
[GRP] => "Group2"
[ITM] => "Item1"
)
[4] => Array
(
[GRP] => "Group2"
[ITM] => "Item2"
)
)
I want to be able to search through the array and sum the amount of items
For the above example the result should be something like 我希望能够搜索数组并求和items
总和。对于上面的示例,结果应为类似
Array
(
["Group1"] => Array
(
["Item1"] => 2
["Item2"] => 1
)
["Group2"] => Array
(
["Item1"] => 1
["Item2"] => 1
)
)
But I have no idea how to approach this. 但是我不知道该如何处理。
I guess the searching is tricky for me. 我想搜索对我来说很棘手。 I though of using someting like this 我虽然用这样的东西
foreach($array as $row){
$grp = $row["GRP"];
$itm = $row["ITM"];
$grpFound = array_search($grp, $newArray);
if($grpFound){
//GRP found, now search for ITM
$itmFound = array_search($grp, $newArray[$grp]);
if($itmFound){
// increase the key value of the item
$newArray[$grp][$itm] += 1
}else{
//Add new item to array group with a item value of 1
$newArray[$grp] = [$itm => 1]
}
}else{
// ADD new group to array
$newArray[] = $grp;
}
}
This is what I have in my head, I know its kind of psuedo-ish code, but please tell me if im on the right track here. 这就是我的想法,我知道它的伪代码,但是请告诉我我是否在正确的轨道上。
You're pretty close - just need a few conditionals within a loop. 您非常接近-循环中只需要一些条件即可。
Working prototype: 工作原型:
$aEntry = array();
$aEntry[ 'GRP' ] = 'Group1';
$aEntry[ 'ITM' ] = 'Item1';
$aEntry2 = array();
$aEntry2[ 'GRP' ] = 'Group1';
$aEntry2[ 'ITM' ] = 'Item2';
$aEntry3 = array();
$aEntry3[ 'GRP' ] = 'Group1';
$aEntry3[ 'ITM' ] = 'Item1';
$aEntry4 = array();
$aEntry4[ 'GRP' ] = 'Group2';
$aEntry4[ 'ITM' ] = 'Item1';
$aEntry5 = array();
$aEntry5[ 'GRP' ] = 'Group2';
$aEntry5[ 'ITM' ] = 'Item2';
$aEntry6 = array();
$aEntry6[ 'GRP' ] = 'Group2';
$aEntry6[ 'ITM' ] = 'Item1';
$aEntry7 = array();
$aEntry7[ 'GRP' ] = 'Group3';
$aEntry7[ 'ITM' ] = 'Item1';
$aData = array();
$aData[] = $aEntry;
$aData[] = $aEntry2;
$aData[] = $aEntry3;
$aData[] = $aEntry4;
$aData[] = $aEntry5;
$aData[] = $aEntry6;
$aData[] = $aEntry7;
$aFormatted = array();
$iCountData = count( $aData );
for( $i = 0; $i < $iCountData; ++$i )
{
$vKeyToAppendTo = '';
foreach( $aFormatted as $sKey => $aValues )
{
if( ( $aValues[ 0 ][ 'GRP' ] == $aData[ $i ][ 'GRP' ] ) )
{
// Set the array key to append to.
$vKeyToAppendTo = $sKey;
break;
}
}
// If we have a key match append.
if( !empty( $vKeyToAppendTo ) )
{
$aFormatted[ $vKeyToAppendTo ][] = $aData[ $i ];
}
// Otherwise create the new lat/lng entry group.
else
{
$aFormatted[ $aData[ $i ][ 'GRP' ] ][] = $aData[ $i ];
}
}
var_dump( $aFormatted );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.