添加到具有键值对的多维数组

时间:2015-03-15 18:05:18

标签: php arrays multidimensional-array

我返回一个类似于这个想法的数组

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

我希望能够搜索数组并总结items的数量 对于上面的示例,结果应该类似于

Array
(
    ["Group1"] => Array
        (
            ["Item1"] => 2
            ["Item2"] => 1
        )
    ["Group2"] => Array
        (
            ["Item1"] => 1
            ["Item2"] => 1
        )
)

但我不知道如何处理这个问题。

我觉得搜索对我来说很棘手。 我虽然使用像这样的东西

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

这就是我的想法,我知道它的伪代码,但请告诉我我是否在正确的轨道上。

1 个答案:

答案 0 :(得分:0)

你非常接近 - 只需要循环中的一些条件。

工作原型:

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