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 cs loadimage运行不了,easyx也下了,没有用
  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析