2012-08-25 98 views
-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)); 

我做用foreach嘗試了for循環的不同組合,但我很難找到任何解決方案。
有人可以幫助我找到正確的方法嗎?
(對不起,如果這太基本了,我真的試圖尋找解決方案,並且我對編程非常陌生,3天前開始學習這個項目)
謝謝!

回答

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 

?> 

現在,您可以管理%

+0

非常感謝你!現在我有一些東西可以在未來幾天內玩;)愛StockOverflow! – RegEx