【问题标题】:unexpected changes - overriding object inside foreach php意外的变化 - foreach php 中的覆盖对象
【发布时间】:2016-12-02 10:53:15
【问题描述】:

我有如下的对象表单数据库数组:

array(3) {
  [1]=>
  array(2) {
    [0]=>
    object(stdClass)#99 (3) {
      ["id"]=>
      string(2) "42"
      ["name"]=>
      string(4) "NAME1"
      ["type"]=>
      string(1) "6"
    }
    [1]=>
    object(stdClass)#98 (3) {
      ["id"]=>
      string(3) "146"
      ["name"]=>
      string(3) "STH1"
      ["type"]=>
      string(1) "2"
    }
  }
  [2]=>
  array(2) {
    [0]=>
    object(stdClass)#97 (3) {
      ["id"]=>
      string(2) "422"
      ["name"]=>
      string(4) "NAME2"
      ["type"]=>
      string(1) "3"
    }
    [1]=>
    object(stdClass)#96 (3) {
      ["id"]=>
      string(3) "16"
      ["name"]=>
      string(3) "STH2"
      ["type"]=>
      string(1) "2"
    }
  }
  [3]=>
  array(2) {
    [0]=>
    object(stdClass)#95 (3) {
      ["id"]=>
      string(2) "11"
      ["name"]=>
      string(4) "NAME3"
      ["type"]=>
      string(1) "5"
    }
    [1]=>
    object(stdClass)#94 (3) {
      ["id"]=>
      string(3) "69"
      ["name"]=>
      string(3) "STH3"
      ["type"]=>
      string(1) "3"
    }
  }
}

如果我想将同一个对象添加到下一个数组并更改其类型的值,我会覆盖当前对象。我该如何解决?我的foreach循环如下:

foreach($events as $key => $event){
    foreach($event as $k => $v){
        if($v->type == 6){
            $v->type = "0";
            $events[$key+1][] = $v;
            $v->type = "6";
        }
    }
}

【问题讨论】:

  • 不清楚您要达到的目标。
  • 我想将对象形式 $events[1][0] 复制到具有不同类型的 $events[2][2](例如 '0')
  • 这个问题和sql有什么关系?
  • 这些数据我从 sql 中得到

标签: php sql object foreach


【解决方案1】:

如果我猜你想要达到的目标是正确的,我会这样做

foreach($events as $key => $event){
    foreach($event as $k => $v){
        if($v->type == 6){
            $tmp = $v;
            $tmp->type="0";
            $events[$key+1][] = $tmp;
        }
    }
}

【讨论】:

  • 任何更改 - 它也会覆盖第一个对象!
  • @jdoe 所以我认为你的问题出在其他地方,首先是有几个具有相同 ID 的对象。如果您通过 id 为事件索引列,则具有相同 id 和不同类型的第二个实例只会更新旧条目
  • 我已经找到了解决方案:stackoverflow.com/a/185939/6648280
猜你喜欢
  • 2018-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 2021-06-20
  • 2018-02-19
相关资源
最近更新 更多