dougehe2022 2015-01-03 13:28
浏览 20
已采纳

php foreach与数组和对象,并重新定义它们的价值

I'm trying to foreach through an array of objects inside an array. I'm not receiving errors, but it seems not to be storing the new value I'm trying to establish. I've found many answers on here closely related to this question, but I'm not understanding, and I'm hoping someone can make this clearer.

Essentially, this converts kg to lbs.

    $kg_conv = 2.20462262;
    $weights = array($data['progress']->weight, $data['progress']->squats,
    $data['progress']->bench, $data['progress']->deadlift); 

    foreach ($weights as $value) {
        $value = $value * $kg_conv;
    }

The values in the array come out unchanged. From what I've read, I should be using $data['progress'] and iterating through that, but I'm not understanding how to refer to only some of the elements inside instead of all of them. I also tried cutting out some redundancy by storing the objects in $progress instead of $data['progress'] but still not success.

UPDATE: The following has not worked

1

    foreach ($weights as &$value) {
        $value = $value * $kg_conv;
    }

2

    foreach ($weights as $key => &$value) {
        $value = $value * $kg_conv;
    }

3

    foreach ($weights as $key => $value) {
        $weights[$key] = $value * $kg_conv;
    }
  • 写回答

4条回答 默认 最新

  • duanlieshuang5330 2015-01-03 14:42
    关注

    it does not work because you do not modify data array, you only modify copy made from this array, which is another array in memory

    Solution: (will work for object's fields too)

    $kg_conv = 2.20462262;
    $weights = ['weight', 'squats','bench', 'deadlift']; 
    
    foreach ($data['progress'] as $key=>&$value) {
      if ( in_array($key,$weights)
        $value = $value * $kg_conv;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致