我有像下面这样的多维数组。
Array
(
[0] => stdClass Object
(
[LOCATIONNAME] => test warehouse
[CATEGORYNAME] => Fruites
[PRODUCTNAME] => 1 - apple
[UNITS] => 8
)
[1] => stdClass Object
(
[LOCATIONNAME] => General
[CATEGORYNAME] => Fruites
[PRODUCTNAME] => 10003 - Grapes
[UNITS] => 7
)
[2] => stdClass Object
(
[LOCATIONNAME] => test warehouse
[CATEGORYNAME] => Fruites
[PRODUCTNAME] => 10003 - Grapes
[UNITS] => 12
)
[3] => stdClass Object
(
[LOCATIONNAME] => General
[CATEGORYNAME] => Standard
[PRODUCTNAME] => 10001 - Chicken Burger
[UNITS] => 12
)
[4] => stdClass Object
(
[LOCATIONNAME] => test warehouse
[CATEGORYNAME] => Standard
[PRODUCTNAME] => 10001 - Chicken Burger
[UNITS] => 17
)
[5] => stdClass Object
(
[LOCATIONNAME] => General
[CATEGORYNAME] => Standard
[PRODUCTNAME] => 10002 - Sandwitch
[UNITS] => 5
)
)
我想用以下数组元素对上面的数组进行分组;
Array
(
[0] => CATEGORYNAME
[1] => PRODUCTNAME
)
我希望将第一个数组与第二个数组元素进行汇总并总结(例如,总结每个仓库的数量)。我已经这样做但我不能按类别汇总元素
我想打印这个数组如下 click to view
是否可以将数组与其他数组元素组合在一起。如果你可以帮助我,那就太棒了。
答案 0 :(得分:0)
确定。根据您的要求,我假设您需要以下格式:
$result = array(
'Standard' => array(
'10001 - Chicken Burger' => array(
array(
'LOCATIONNAME' => 'General',
'UNITS' => 5
),
array(
'LOCATIONNAME' => 'test warehouse',
'UNITS' => 17
),
),
'10002 - Sandwitch' => array(
array(
'LOCATIONNAME' => 'General',
'UNITS' => 5
)
)
)
);
为此,代码将是:
$result = array();
foreach ($objects as $obj) {
if (!is_array($result[$obj->CATEGORYNAME])) {
$result[$obj->CATEGORYNAME] = array();
}
if (!is_array($result[$obj->CATEGORYNAME][$obj->PRODUCTNAME])) {
$result[$obj->CATEGORYNAME][$obj->PRODUCTNAME] = array();
}
$temp = array(
'LOCATIONNAME' => $obj->LOCATIONNAME,
'UNITS' => $obj->UNITS
);
array_push($result[$obj->CATEGORYNAME][$obj->PRODUCTNAME], $temp);
}
所以根据上面的输出,您可以按如下方式打印表格:
<?php
$result = array(
'Standard' => array(
'10001 - Chicken Burger' => array(
array(
'LOCATIONNAME' => 'General',
'UNITS' => 5
),
array(
'LOCATIONNAME' => 'test warehouse',
'UNITS' => 17
),
),
'10002 - Sandwitch' => array(
array(
'LOCATIONNAME' => 'General',
'UNITS' => 5
)
)
)
);
?>
<html>
<head>
<title>Test Table</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
</head>
<body>
<table class="table table-bordered">
<thead>
<tr>
<th>Location</th>
<th>Units</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $category => $catDetails) { ?>
<tr>
<td colspan="2"><?php echo $category; ?></td>
</tr>
<?php foreach ($catDetails as $product => $items) { ?>
<tr>
<td colspan="2"><?php echo $product; ?></td>
</tr>
<?php foreach ($items as $item) { ?>
<tr>
<td><?php echo $item['LOCATIONNAME']; ?></td>
<td><?php echo $item['UNITS']; ?></td>
</tr>
<?php } } } ?>
</tbody>
</table>
</body>
希望这有帮助。