我说英语不太好,不确定标题所以会试着解释我需要做什么:
我正在制作日志解析器。 我有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));
我确实尝试过使用foreach的for循环的不同组合,但我很难找到任何解决方案
有人可以帮助我做正确的方法吗?
(对不起,如果这太基础了,我真的试图寻找解决方案,我是一个非常新的编程,3天前开始学习这个项目)
谢谢!
答案 0 :(得分: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
?>
现在您可以管理%
。