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条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)