如何在PHP中从两个相关的关联数组中打印元素和值

时间:2013-09-27 22:32:58

标签: php arrays

我有两个关联数组。 $dpt_total是一个部门列表,以及这些部门的总数。 $cl_subtotal是一个部门,类和小计的多维数组。

我想显示部门和总数,然后显示与该部门相关联的类以及该类的小计。 例如:

vdump($dpt_total);

array(2) {
'None' → float 132.88
'instore bakery' → float 786.24
}

Sizes: 2

vdump($cl_subtotal);

array(2) {
 'None' → array(1) {
 'None' → float 132.88
 }

'instore bakery' → array(10) {
  'pies' → float 70.94
  'cakes' → float 146.71
  'miscellaneous' → float 25.57
  'cookies' → float 52.38
  'brownies' → float 33.96
  'rolls' → float 143.02
  'danish' → float 90.42
  'bagels & pretzels' → float 85.68
  'breads' → float 55.73
  'dessert case' → float 81.83
 }
}

应显示以下内容:

Department     Class     Total
--------------------------------
None                     132.88
               None      132.88
Instore Bakery           786.24
               pies      70.94
               cakes     146.71
               misc      25.57
               cookies   52.38
              (and so on)

2 个答案:

答案 0 :(得分:2)

一个简单的嵌套foreach语句可以得到你想要的东西:

foreach($cl_subtotal as $department=>$classes){
    //formatting
    //also note you can use $department as a key for $dpt_total ex:
    //$dpt_total[$department] will give you the total for the department
    foreach($classes as $class=>$price){
        //formatting
    }
}

答案 1 :(得分:0)

希望这有帮助。

$tbl=array();
foreach($dpt_total as $key=>$val){
    $row=array($key,'',$val);
    $tbl[]=$row;
    $tmp=$cl_subtotal[$key];
    foreach($tmp as $key2=>val2){
        $row=array('',$key,$val);
        $tbl[]=$row;
    }
}

$table='<table><tr><th>Department</th><th>Class</th><th>Total</th></tr>'
foreach($tbl as $row){
    $table.='<tr>';
    foreach($row as $col){
        $table.='<td>'.$col.'</td>';
    }
    $table.='/<tr>';
}
$table.='</table>';