我需要有关foreach
和PHP中数组的帮助
说我有以下数组:
$orders = array (
0 =>
array (
'company' => 'Company 1',
'total' => '5',
),
1 =>
array (
'company' => 'Company 2',
'total' => '10',
),
2 =>
array (
'company' => 'Company 1',
'total' => '15',
),
3 =>
array (
'company' => 'Company 1',
'total' => '5',
),
4 =>
array (
'company' => 'Company 3',
'total' => '12',
)
);
公司1的订单1为5 公司2的订单2为10 公司1的订单3为15 公司2的订单4为5 公司3的订单5为12
我希望输出显示公司名称和每家公司订单的累计总数
例如:
Company 1 20
Company 2 15
Company 3 12
答案 0 :(得分:2)
只需创建另一个跟踪订单的数组。
/etc/apache2/mods-enabled/
首先,我们检查公司是否已经在公司阵列中,如果是,那么我们将总数添加到该公司的当前总数中。
否则,我们只需创建一个新密钥并存储总数。
此外,您可以将$companies = array();
foreach ($orders as $order) {
if (array_key_exists($order["company"], $companies)) {
$companies[$order["company"]] += $order["total"];
} else {
$companies[$order["company"]] = $order["total"];
}
}
写入类型转换为整数
这可能有助于确保您拥有正确的数据。
答案 1 :(得分:2)
array_reduce()
解决方案:
$groups = array_reduce($orders, function($r, $a) {
$k = $a['company'];
(isset($r[$k]))? $r[$k] += $a['total'] : $r[$k] = $a['total'];
return $r;
}, []);
foreach ($groups as $k => $v) {
printf("%-20s%d\n", $k, $v);
}
输出:
Company 1 25
Company 2 10
Company 3 12
答案 2 :(得分:1)
使用foreach循环执行此操作的一种方法是增加某个变量:
// Your array
$array = array(...);
// Init of the sum of each total for each company
$c1 = 0;
$c2 = 0;
$c3 = 0;
// You loop through your array and test the output
foreach ($array as $order => $value_array) {
switch($value_array['company']) {
case 'Company 1' : $c1 += intval($value_array['total']); break;
case 'Company 2' : $c2 += intval($value_array['total']); break;
case 'Company 3' : $c3 += intval($value_array['total']); break;
}
}
//$c1 will be the sum for company 1;
//$c2 for the company 2;
//$c3 for the company 3.
这是你在找什么?
答案 3 :(得分:0)
另一种方式:array_walk
$result = array();
array_walk($orders, function ($element) use (&$result) {
$company = $element['company'];
if (!isset($result[$company]))
$result[$company] = 0;
$result[$company] += $element['total'];
});
对于此输入:
$orders = array(
0 =>
array(
'company' => 'Company 1',
'total' => '5',
),
1 =>
array(
'company' => 'Company 2',
'total' => '10',
),
2 =>
array(
'company' => 'Company 1',
'total' => '15',
),
3 =>
array(
'company' => 'Company 1',
'total' => '5',
),
4 =>
array(
'company' => 'Company 3',
'total' => '12',
)
);
输出将是:
array(3) {
["Company 1"]=>
int(25)
["Company 2"]=>
int(10)
["Company 3"]=>
int(12)
}