douqiao4450 2014-07-01 15:54
浏览 56
已采纳

PHP在保持其位置的同时重命名对象属性

How can I rename an object property without changing the order?

Example object:

$obj = new stdClass();
$obj->k1 = 'k1';
$obj->k2 = 'k2';
$obj->k3 = 'k3';
$obj->k4 = 'k4';

Example rename by creating new property:

$obj->replace = $obj->k3;
unset($obj->k3);

Result:

( k1=>k1, k2=>k2, k4=>k4, replace=>k3 )

See the problem?

Simply recreating the object property causes the order to change.

I had a similar issue with arrays and came up with this solution:

Implemented solution for arrays

function replaceKey(&$array, $find, $replace)
{
    if(array_key_exists($find, $array)){
        $keys = array_keys($array);     
        $i = 0;
        $index = false;
        foreach($array as $k => $v){
            if($find === $k){
                $index = $i;
                break;
            }
            $i++;
        }
        if ($index !== false) {
            $keys[$i] = $replace;
            $array = array_combine($keys, $array);
        }
    }        
}

Looking for something similar to this but a function that will work on objects.

Can't seem to find any documentation on object property position indexes.

  • 写回答

2条回答 默认 最新

  • dongluolie3487 2014-07-04 02:09
    关注

    So, readd your properties

    $obj = new YourClass();
    $backup = [];
    foreach ($obj as $key => $value)
        {
        $backup[$key] = $value;
        unset($obj->$key);
        }
    replaceKey($backup, $find, $replace);
    foreach ($backup as $key => $value)
        {
        $obj->$key = $value;
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。