dongtun2572
2018-05-16 09:58
浏览 53
已采纳

动态多维数组值使用php计数

I am trying to count the array value in the multidimensional array for the following Array value.

$allMultiGridRes = Array
(
    [0] => Array
        (
            [1] => Array
                (
                    [1] => grid multi col1
                    [2] => grid multi col2
                )
            [2] => Array
                (
                    [1] => grid multi col1
                )
        )
    [1] => Array
        (
            [1] => Array
                (
                    [1] => grid multi col1
                    [2] => grid multi col2
                )
            [2] => Array
                (
                    [1] => grid multi col1
                    [2] => grid multi col2
                )
        )
    [2] => Array
        (
            [1] => Array
                (
                    [1] => grid multi col1
                    [2] => grid multi col2
                )
            [2] => Array
                (
                    [1] => grid multi col1
                    [2] => grid multi col2
                )
        )
)

I am expecting the following output.

Array
(
    [1] => Array
        (
            [grid multi col1] => 3
            [grid multi col2] => 3
        )
    [2] => Array
        (
            [grid multi col1] => 3
            [grid multi col2] => 2
        )
)

I have tried the following method using the for loop but I cannot able to achieve the above output like above.

$allMultiGridRes =array();
$paramCheck =array();
foreach ($allMultiGridRes as $gMKey => $GMvalue){
    if(!empty($GMvalue)){
        foreach ($GMvalue as $gMKey2 => $gMValue2){
            if(!empty($gMValue2)){
                $allGridCount[$gMKey2] = array_count_values($gMValue2);
                foreach ($gMValue2 as $gMKey3 => $gMValue3){
                    $paramCheck = !empty($allGridCount[$gMKey2])?$allGridCount[$gMKey2]:array();
                    $GMindex1 = $gMValue3;
                    $allGridCount[$gMKey2][$GMindex1] = array_key_exists($GMindex1,$paramCheck) ? $allGridCount[$gMKey2][$GMindex1]++ : 1;
                    }
                }
            }
        }
    }
}

Using this method I am getting the following output but value are not counting as expected.

Array
(
    [1] => Array
        (
            [grid multi col1] => 1
            [grid multi col2] => 1
        )
    [2] => Array
        (
            [grid multi col1] => 1
            [grid multi col2] => 1
        )
)

I am open to suggestions also I have tried a lot of methods but still I cannot achieve it. I am stuck here for long time

Thanks in advance.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题