dongxianrang9269 2015-04-27 16:00
浏览 34
已采纳

是否将数组值转换为类属性资源密集型?

I have an array with approximately 50 keys & values. I would like to take the array and create class properties from the values like so:

$arr = array();
$arr['name'] = 'John';
$arr['age'] = '20';

$object = (object) $arr;

echo $object->name;

My question is, is this very resource-intensive? Would it require a lot of overhead with a large array? If so, would there be a better way of doing this?

Also, this does not work if the array is setup like:

$arr = array();
$arr['name']['boy'] = 'John';
$arr['name']['girl'] = 'Jane';
$arr['age']['boy'] = '20';
$arr['age']['girl'] = '30';

$object = (object) $arr;

echo $object->name->boy;
  • 写回答

2条回答 默认 最新

  • dongmu1390 2015-04-27 16:14
    关注

    You can make like this :

    $arr = array();
    
    $arr['name']['boy'] = 'John';
    $arr['name']['girl'] = 'Jane';
    $arr['age']['boy'] = '20';
    $arr['age']['girl'] = '30';
    
    
    $obj = json_decode(json_encode($arr)); //Turn it into an object
    
    
    print_r($obj);    // to view the result
    
    echo $obj->name->boy;   // output: John
    

    It works great with simple arrays and with subarrays too.

    I think this is good solution when we work with subarrays and we want to save resources

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

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line