如果数组存在,则在数组上添加值

时间:2017-08-18 02:33:49

标签: php

如果存在,我想在我的数组上添加一个值。如果不存在则创建一个新值。

  $orders = array(
              array("qty" => 3,"piece_type"=> "Documents (Up to 1kg)"),
              array("qty" => 2,"piece_type"=> "Documents (Up to 1kg)"),
              array("qty" => 4,"piece_type"=> "Large (10-20kg 150cm)")
              );

$sizes = array(
    "Documents (Up to 1kg)"=>10,
    "Large (10-20kg 150cm)"=>20
);

$wpc_total_cost = array();
$i = 0;

foreach( $orders as $value )
{     
  $i++; 
  $wpc_total_cost[$value['piece_type']] += $value['qty'] * $sizes[$value['piece_type']];
}

print_r($wpc_total_cost);

我尝试过array_exist我不太了解逻辑。

我的错误:

NOTICE Undefined index: Documents (Up to 1kg) on line number 21

NOTICE Undefined index: Large (10-20kg 150cm) on line number 21
Array ( [Documents (Up to 1kg)] => 50 [Large (10-20kg 150cm)] => 80 )

2 个答案:

答案 0 :(得分:1)

尝试使用array_key_exists。我创建了一个名为$cost的变量,这样公式就不会在两个地方重复了。

$orders = array(
    array("qty" => 3,"piece_type"=> "Documents (Up to 1kg)"),
    array("qty" => 2,"piece_type"=> "Documents (Up to 1kg)"),
    array("qty" => 4,"piece_type"=> "Large (10-20kg 150cm)")
);

$sizes = array(
    "Documents (Up to 1kg)"=>10,
    "Large (10-20kg 150cm)"=>20
);

$wpc_total_cost = array();
$i = 0;

foreach( $orders as $value )
{
    $i++;

    $cost = $value['qty'] * $sizes[$value['piece_type']];

    if(array_key_exists($value['piece_type'], $wpc_total_cost)){
        $wpc_total_cost[$value['piece_type']] += $cost;
    } else {
        $wpc_total_cost[$value['piece_type']] = $cost;
    }
}

print_r($wpc_total_cost);

答案 1 :(得分:0)

问题出在这一行:

$wpc_total_cost[$value['piece_type']] += $value['qty'] * $sizes[$value['piece_type']];

操作+=实际上意味着:

$wpc_total_cost[$value['piece_type']] = $wpc_total_cost[$value['piece_type']] + $value['qty'] * $sizes[$value['piece_type']];

注意,我们在表达式的右侧使用$wpc_total_cost[$value['piece_type']],这意味着它应该被定义,但是在foreach循环的第一次迭代中不存在。

一个快速解决方法是使用:

if (!isset($wpc_total_cost[$value['piece_type']]))
    $wpc_total_cost[$value['piece_type']] = 0;
$wpc_total_cost[$value['piece_type']] += $value['qty'] * $sizes[$value['piece_type']];