duanguoyin7008 2017-08-18 02:33
浏览 36
已采纳

在数组上添加值(如果存在)

I wanted to add a value on my array if it exist.If not then create a new one.

  $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);

I tried array_exist I don't quite get the logic.

my error :

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条回答 默认 最新

  • douying4203 2017-08-18 02:44
    关注

    the problem is in this line:

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

    operation += actually means this:

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

    Note, that we're using $wpc_total_cost[$value['piece_type']] on right side of the expression, it means that it should be defined, but on first iteration of foreach loop is does not exists.

    One quick fix is to use:

    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']];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?