加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 为什么我无法在关联数组中添加新的键值对?

发布时间:2020-12-13 17:31:12 所属栏目:PHP教程 来源:网络整理
导读:我有一个名为$data的大型关联数组.为了您的理解,我打印下面的一个元素. Array( [0] = Array ( [id] = 92 [zip_code] = 07080 [phone_no] = 7327630062 [amount] = [currency] = $ [product_details] = Array ( ) ) [1] = Array ( [id] = 93 [zip_code] = 070
我有一个名为$data的大型关联数组.为了您的理解,我打印下面的一个元素.

Array
(
    [0] => Array
        (

            [id] => 92
            [zip_code] => 07080
            [phone_no] => 7327630062
            [amount] => 
            [currency] => $
            [product_details] => Array
                (
                )

        )
    [1] => Array
        (

            [id] => 93
            [zip_code] => 07081
            [phone_no] => 7327630063
            [amount] => 20
            [currency] => $
            [product_details] => Array
                (
                )

        )
)

现在我想在名为$data的上述关联数组的每个元素中创建一个新的键值对.为此,我写了以下逻辑,但它没有创建一个新的键值对.有人可以帮我这方面吗?

foreach($data as $key => $value) {
        if(!empty($value['amount'])) { 
          $value['final_amount'] = $value['amount'] - 2;
        } else 
          $value['final_amount'] = '';        
      }

解决方法

从 manual of foreach:

In order to be able to directly modify array elements within the loop
precede $value with &. In that case the value will be assigned by
reference.

foreach($data as $key => &$value)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读