PHP:计算信息数量

时间:2017-11-28 21:36:52

标签: php arrays csv

我将CSV磁贴导入数组。 CSV文件如下所示:

Company1, Workstation, PC1
Company1, Workstation, PC2
Company1, Server, Server1
Company2, Workstation, PC1
Company2, Server, Server1

我想要做的是,计算公司1有多少工作站,公司2有多少台服务器,等等。

我喜欢这样的结果: Company1(可变名称): 电脑:xxx 服务器:xx

我看过array_count_values,但似乎无法让它工作,所以如果有任何帮助我将不胜感激。

3 个答案:

答案 0 :(得分:0)

我认为您正在尝试做类似的事情:

// Sample input data
$arrayFromCsv = [
    ['Company1', 'Workstation', 'PC1'],
    ['Company1', 'Workstation', 'PC2'],
    ['Company1', 'Server', 'Server1'],
    ['Company2', 'Workstation', 'PC1'],
    ['Company2', 'Server', 'Server1'],
];

// Data transformation
$inventory = [];
foreach ($arrayFromCsv as $row) {
    if (!isset($inventory[$row[0]])) {
        $inventory[$row[0]] = [];
    }

    if (!isset($inventory[$row[0]][$row[1]])) {
        $inventory[$row[0]][$row[1]] = 0;
    }

    $inventory[$row[0]][$row[1]]++;
}

// To get workstation count for Company1:
$company = 'Company1';
$type = 'Workstation';

if (isset($inventory[$company][$type])) {
    echo "$company has {$inventory[$company][$type]} $type(s)";    
}

答案 1 :(得分:0)

首先需要对它们进行分组,然后在第二个循环中显示它们。

代码:(Demo

$array=[
    ['Company1', 'Workstation', 'PC1'],
    ['Company1', 'Workstation', 'PC2'],
    ['Company1', 'Server', 'Server1'],
    ['Company2', 'Workstation', 'PC1'],
    ['Company2', 'Server', 'Server1']
];

// group the occurrences in a 2-level array
foreach($array as $row){
    if(!isset($group[$row[0]][$row[1]])){
        $group[$row[0]][$row[1]]=1;
    }else{
        ++$group[$row[0]][$row[1]];
    }
}
// display results
foreach($group as $company=>$subarray){
    echo "\n$company:";
    foreach($subarray as $key=>$num){
        echo " $key: $num";
    }
}

输出:

Company1: Workstation: 2 Server: 1
Company2: Workstation: 1 Server: 1

答案 2 :(得分:-1)

使用像

这样的公司创建一个数组
$array['Company1']['Workstation'] ++
$array['Company1']['Server'] ++

下一个

count( $array['Company1']['Workstation'] );

我认为最简单的方式。