如何在多维数组中搜索特定索引并更新其值?

时间:2014-06-04 07:57:57

标签: php arrays multidimensional-array

以下是我的代码:

我从数据库中获取成分记录,每条记录都包含idnameweight以及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鸡

<3> 3KG鸡

我想要的是:

4KG鸡

以及其他类别的成分。

因此,上述foreach循环将针对每个成分类别运行。

我无法以某种方式处理如何使用多维数组。任何人都可以帮忙,我该怎么做?如果您需要更多详细信息,请与我们联系。谢谢。

2 个答案:

答案 0 :(得分:1)

要总结它们,您需要从中创建另一个数组,它们在循环内部对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
        )

)

答案 1 :(得分:0)

如果结果数组的键不重要,您可以执行以下操作:

$result = array();

foreach ($ingredients as $ingredient) {
    if (isset($result[$ingredient['id']]))
        $result[$ingredient['id']]['weight'] += $ingredient['weight'];
    else
        $result[$ingredient['id']] = $ingredient;
}

项目的ID存储在$result的密钥中,并在检查项目是否已存在时使用。