2

我正在尝试确定多维关联数组中每个数组的计数。例如,如果我有一个像这样的数组:

Array
(
    [food] => Array
        (
            [soup] => Array
                (
                    [chicken noodle] => 
                    [tomato] => 
                    [french onion] => 
                )

            [salad] => Array
                (
                    [house] => 
                    [ceasar] =>
                )

        )
    [drink] => Array
        (
            [soda] => Array
                (
                    [coke] => 
                    [sprite] => 
                    [dr pepper] => 
                )

            [alcoholic] => Array
                (
                    [whiskey] => Array
                        (
                            [Jim Beam] => 
                            [Jameson] =>
                            [Bushmills] =>
                        )
                    [vodka] => Array
                        (
                            [Stolichnaya] => 
                            [Ketel One] =>
                            [Grey Goose] =>
                            [Belvedere] =>
                        )
                    [rum] => Array
                        (
                            [Captain Morgan] => 
                            [Bacardi] =>
                        )
                )
        )
)

不太清楚如何解释,所以我会尽力而为。我想找出数组中每个数组的计数。所以我期望从这个数组中得到的值看起来像:

Array
(
        // total count of all arrays at  "level 1" (i.e. food & drink)
        [0] => 2
        // total count of all arrays at  "level 2" (i.e. soup, salad, soda, alcoholic)
        [1] => 4
        // total count of all arrays at  "level 3" (i.e. chicken noodle, tomato, french onion, house, ceasar, coke, sprite, dr pepper, whiskey, vodka, rum)
        [2] => 11
        // total count of all arrays at  "level 4" (i.e. Jim Beam, Jameson, Bushmills, Stolichnaya, Ketel One, Grey Goose, Belvedere, Captain Morgan, Bacardi)
        [3] => 9
)

现在我知道我只对值使用索引键而不是值,如果数组是标准索引数组,则更容易获取这些值(我认为我使用的是正确的术语在这里,请随时纠正我——当然,重点是让我在这里理解——而不是让某人只是“给我一个答案”:))因为我可以循环遍历数组for($i = 0 $i < count($array); $i++)并增加我的计数因此。我已经在 SO 中搜索过这样的问题,但没有找到,如果我错过了,请随时简单地指出它。谢谢!

解决方案!(阅读评论以了解对话流程)

class Test {

        public function getCounts($data) {
            $levels = array();
            $counts = $this->calc($levels, 0, $data);
            return $counts;
        }

        private function calc(&$levels, $current, $parent) {
            if(!isset($levels[$current])) {
                $levels[$current] = 0;
            }
            foreach($parent as $child) {
                $levels[$current]++;
                if(is_array($child)) {
                    $this->calc($levels, $current+1, $child);
                }
            }
            return $levels;
        }

    }

    $test = new Test();

    $data['food']['soup']['chicken_noodle'] = '';
    $data['food']['soup']['tomato'] = '';
    $data['food']['soup']['french onion'] = '';
    $data['food']['salad']['house'] = '';
    $data['food']['salad']['ceasar'] = '';
    $data['drink']['soda']['coke'] = '';
    $data['drink']['soda']['sprite'] = '';
    $data['drink']['soda']['dr pepper'] = '';
    $data['drink']['alcoholic']['whiskey']['Jim Beam'] = '';
    $data['drink']['alcoholic']['whiskey']['Jameson'] = '';
    $data['drink']['alcoholic']['whiskey']['Bushmills'] = '';
    $data['drink']['alcoholic']['vodka']['Stolichnaya'] = '';
    $data['drink']['alcoholic']['vodka']['Ketel One'] = '';
    $data['drink']['alcoholic']['vodka']['Grey Goose'] = '';
    $data['drink']['alcoholic']['vodka']['Belvedere'] = '';
    $data['drink']['alcoholic']['rum']['Captain Morgan'] = '';
    $data['drink']['alcoholic']['rum']['Bacardi'] = '';

    $counts = $test->getCounts($data);

    echo '<pre>';
    print_r($counts);
    exit('</pre>');

    // Prints the following

    // Array
    // (
    //     [0] => 2
    //     [1] => 4
    //     [2] => 11
    //     [3] => 9
    // )
4

2 回答 2

1

更新#2。很多信息,如果我失去你,请告诉我。

我在最后一个代码中犯了几个小错误(需要通过$current + 1而不是$current++,并且$levels[$current]++在错误的位置)。我用你的示例数据测试了这个更新;它会为你工作。基本上,calc()它是一个递归函数,它遍历数组的每一级,计算作为数组的每个索引,并将该计数添加到主“计数”数组 ( $levels)。就像我在下面所做的那样,您可以将其直接粘贴到您的课程中。

它不会故意返回任何东西。$levels通过引用传递的,每一层的计数直接在上面更新。因此,您传递给的第一个变量calc()将变成一个数组,就像您在问题中寻找的那个一样。

如果你的类脚本看起来完全一样,你应该得到错误。之后class someName {,您应该只定义函数和变量。实际执行操作的代码,例如 usingecho或 setting $test = new Test();,需要放在类定义之后。

话虽如此,如果您希望每次启动此类时都执行一些代码,则应将此代码放在类的构造函数中。

以下是我认为您希望您的班级看起来的样子。如果您希望 $data 在类中,请声明变量var $data并将其填充到构造函数中。如果您感到困惑,请告诉我,我可以再次更新我的答案。

// Your class
class Test
{
    // Counts the number of arrays in each level of $data
    function calc(&$levels, $current, $parent)
    {
        if (!isset($levels[$current])) {
            $levels[$current] = 0;
        }
        foreach($parent as $child) {
            $levels[$current]++;
            if (is_array($child)) {
                $this->calc($levels, $current + 1, $child);
            }
        }
    }
}

// Let's use the class! Create an instance of it
$test = new Test();

// Fill the data array
$data = array();
$data['food']['soup']['chicken_noodle'] = '';
$data['food']['soup']['tomato'] = '';
$data['food']['soup']['french onion'] = '';
$data['food']['salad']['house'] = '';
$data['food']['salad']['ceasar'] = '';
$data['drink']['soda']['coke'] = '';
$data['drink']['soda']['sprite'] = '';
$data['drink']['soda']['dr pepper'] = '';
$data['drink']['alcoholic']['whiskey']['Jim Beam'] = '';
$data['drink']['alcoholic']['whiskey']['Jameson'] = '';
$data['drink']['alcoholic']['whiskey']['Bushmills'] = '';
$data['drink']['alcoholic']['vodka']['Stolichnaya'] = '';
$data['drink']['alcoholic']['vodka']['Ketel One'] = '';
$data['drink']['alcoholic']['vodka']['Grey Goose'] = '';
$data['drink']['alcoholic']['vodka']['Belvedere'] = '';
$data['drink']['alcoholic']['rum']['Captain Morgan'] = '';
$data['drink']['alcoholic']['rum']['Bacardi'] = '';    

// Count the data for arrays on each level
$count = array();
$test->calc($count, 0, $data);

// Print the results
echo '<pre>';
print_r($count);
exit ('</pre>');
于 2012-06-03T03:49:40.860 回答
0

如果要获取所有数组中所有元素的总和,可以使用

count($arr, COUNT_RECURSIVE);

在线尝试

于 2019-07-17T14:07:03.243 回答