-1

我的英语不是很好,不确定标题,所以会尝试解释我需要做什么:

我正在制作日志解析器。我有 3 个包含相应元素的动态数组(从 .log 文件中读取):

$personName //array of strings, can contain same name
$itemName   //array of strings, can contain same name
$itemAmount //array of numbers

示例数组:

$personName = array("Adam", "Maria", "Adam", "Adam");
$itemName = array("paper", "paper", "pen", "paper");
$itemAmount = array(11, 25, 2, 64);

我想对这些数组进行排序(按人和项目)和计数(按数量),例如。打印:

Total there are '100' 'paper' and '2' 'pen'.
'Adam' have '75' 'paper' and '2 'pen'.
'Maria' have '25' 'paper'.

这将允许我获得每个人拥有的每个项目的百分比,例如:

'Adam' have '75'% of all 'paper' and '100'% of all 'pen'.
'Maria' have '25'% of all 'paper'.

我有具有唯一名称的数组:

$persons = array_keys (array_flip ($personName));
$items = array_keys (array_flip ($itemName));

我确实尝试了 for 循环与 foreach 的不同组合,但我很难找到任何解决方案。
有人可以帮我找到正确的方法吗?
(对不起,如果这太基本了,我真的试图寻找解决方案,我对编程很陌生,3天前开始学习这个项目)
谢谢!

4

1 回答 1

0

像这样:

<?php
    $personName = array("Adam", "Maria", "Adam", "Adam", "Mihai");
    $itemName = array("paper", "paper", "pen", "paper", 'pencil');
    $itemAmount = array(11, 25, 2, 64, '18');


    $items = array();
    $persons = array();
    foreach($itemName as $id => $name){
        $items[$name] += $itemAmount[$id]; // we are adding amount for each item to $items array
        $persons[$personName[$id]][$name] += $itemAmount[$id]; // we are adding every item with amount to each persons
    }

    echo "Total there are "; // we are looping in each $items to display totals
    $i = 0;
    foreach($items as $nr => $item){

        echo "'".$item."' '".$nr."'";

        if($i < count($items)-2){ // this is for 'and' or ',' in case of multiple items
            echo ", ";
        } elseif($i < count($items)-1){
            echo " and ";
        }
        $i++;
    }

    echo '<br />';

    foreach($persons as $one => $value ){ // we are looping in each persons to display what they have
        echo "'".$one."' have ";
        $i = 0;
        foreach($value as $val => $number){

            echo "'".$number."' '".$val."'";

            if($i < count($value)-2){ // this is for 'and' or ',' in case of multiple items
                echo ", ";
            } elseif($i < count($value)-1){
                echo " and ";
            }

            $i++;
        }
        echo '.<br />';

    }

    // print_r($items); // will result in all items
    // print_r($persons); // will result in every person with every item

?>

现在您可以管理%.

于 2012-08-25T00:34:46.017 回答