dtz88967 2013-08-29 07:30
浏览 102
已采纳

PHP循环遍历对象数组会产生意外结果

I have the following PHP code to set parentId for each post. The parentId of each data all become the last post ID. What's wrong with my logic?

btw, if I change it to array, everythings becomes ok. Please help!

$data = array(
    (object)array('name' => 'myname')
);
$posts = array(
    (object)array('ID' => 1, 'data'=>$data),
    (object)array('ID' => 2, 'data'=>$data),
    (object)array('ID' => 3, 'data'=>$data)
);
foreach($posts as &$post){
    $post->data[0]->parentId = $post->ID;
}
print '<pre>';print_r($posts);die;
die;

Results:

Array
(
    [0] => stdClass Object
        (
            [ID] => 1
            [data] => Array
                (
                    [0] => stdClass Object
                        (
                            [name] => myname
                            [parentId] => 3 // expect to be 1
                        )

                )

        )

    [1] => stdClass Object
        (
            [ID] => 2
            [data] => Array
                (
                    [0] => stdClass Object
                        (
                            [name] => myname
                            [parentId] => 3 // expect to be 2 !!!
                        )

                )

        )

    [2] => stdClass Object
        (
            [ID] => 3
            [data] => Array
                (
                    [0] => stdClass Object
                        (
                            [name] => myname
                            [parentId] => 3
                        )

                )

        )

)
  • 写回答

2条回答 默认 最新

  • duanpengya7074 2013-08-29 07:35
    关注

    All things considered, the real issue here is, after a second glance at your code, the way you're setting the data property. Since PHP5, objects are passed/assigned by reference by default. Remember the PHP4 days? ($newInstance = &new SomeClass();), PHP5 uses references for objects now, so when you do:

    $data = array(
        (object)array('name' => 'myname')//create object
    );
    

    Then, all three objects are assigned the same object (By reference!), so if you change it for the first time around, all three instances will reflect the same change!

    I've recently posted a lengthy answer on references in loops here, it might be worth a look, because looping by reference isn't the best way to go about your business.

    Some code-review:
    Instead of constructing all these arrays, and cast them to objects individually, I'd just do this:

    $data = array(
        array('name' => 'myname')
    );
    $posts = array(
        array('ID' => 1, 'data'=>$data),
        array('ID' => 2, 'data'=>$data),
        array('ID' => 3, 'data'=>$data)
    );
    foreach($posts as $k => $post)
    {
        $posts[$k]['data'][0]['parentId'] = $posts[$k]['ID'];
    }
    $posts = json_decode(json_encode($posts));//turns everything into objects
    print_r($posts);
    

    At first, it might seem inefficient to json_encode something, just to json_decode it, but json_decode returns objects, instead of associative arrays by default. I've ran a few tests scripts not too long ago, as it turned out: the encode-decode approach was actually faster than casting each associative array...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗