下面是我的代码:
我从数据库中获取配料记录,每个记录都包含id、name和weight以及category字段。
我想把所有有相同id的成分的重量相加
$weights=array();
foreach($ingredients as $ingredient)
{
$key=array_search($ingredient['id'],$weights);
if($key==true)
{
//Sum weights
}
else
{
$new_ingredient=array('id'=>$ingredient['id'],'weight'=>$ingredient['weight']);
array_push($weights, $new_ingredient);
}
}
print_r($weights);目前,我有以下情况:
肉类:
1KG鸡
3KG鸡
我想要的是:
4KG鸡
等等,为其他类别的成分。
因此,上面的foreach循环将对每个成分类别运行。
我无法用多维数组来处理如何做到这一点。有人能帮忙吗,我该怎么做?如果你需要更多的细节,请告诉我。谢谢。
发布于 2014-06-04 08:23:47
要将它们全部加起来,您需要创建另一个数组,它们在循环中与weight键相加。考虑一下这个例子:
// if your db query result looks like this (we dont know what your original data looks like)
// sample data from select * from ingredients
$values_from_db = array(
array(
'id' => 1,
'name' => 'Chicken',
'unit' => 'KG',
'weight' => 100,
),
array(
'id' => 2,
'name' => 'Pork',
'unit' => 'KG',
'weight' => 300,
),
array(
'id' => 3,
'name' => 'Beef',
'unit' => 'KG',
'weight' => 400,
),
array(
'id' => 1,
'name' => 'Chicken',
'unit' => 'KG',
'weight' => 100,
),
array(
'id' => 2,
'name' => 'Pork',
'unit' => 'KG',
'weight' => 200,
),
);
$data = array();
foreach($values_from_db as $key => $value) {
$current_id = $value['id'];
if(!isset($data[$current_id]['weight'])) $data[$current_id]['weight'] = 0;
$data[$current_id]['id'] = $current_id;
$data[$current_id]['name'] = $value['name'];
$data[$current_id]['unit'] = $value['unit'];
$data[$current_id]['weight'] += $value['weight'];
}
echo "<pre>";
print_r($data);
echo "</pre>";样本输出:
Array
(
[1] => Array
(
[weight] => 200
[id] => 1
[name] => Chicken
[unit] => KG
)
[2] => Array
(
[weight] => 500
[id] => 2
[name] => Pork
[unit] => KG
)
[3] => Array
(
[weight] => 400
[id] => 3
[name] => Beef
[unit] => KG
)
)发布于 2014-06-04 08:22:16
如果结果数组的键不重要,可以执行以下操作:
$result = array();
foreach ($ingredients as $ingredient) {
if (isset($result[$ingredient['id']]))
$result[$ingredient['id']]['weight'] += $ingredient['weight'];
else
$result[$ingredient['id']] = $ingredient;
}项目的id存储在$result键中,并在检查项目是否已经存在时使用。
https://stackoverflow.com/questions/24031980
复制相似问题