dtng25909 2014-07-09 12:14
浏览 19
已采纳

如何访问以下属性?

If I want to cast an index array to an object, is there a way to access the properties (with the -> operator) that were created in according to the array elements?

<?php
$numeric_index_array = array(10, 20, 30) ;

$obj_numeric_index = (object)$numeric_index_array ;

var_dump($obj_numeric_index) ;
  • 写回答

1条回答 默认 最新

  • dorv56831 2014-07-09 12:36
    关注

    You cannot access field if there is only digits. When you cast an object to a simple one dimensional array, fields are numbers.

    array(10, 20, 30); // same as: array(0 => 10, 1 => 20, 2 => 30);
    

    The only way is to create a two dimensional array with some chars. Example :

    <?php
    $numeric_index_array = array('1.' => 10, 2 => 20, '3' => 30) ;
    
    $obj_numeric_index = (object)$numeric_index_array ;
    
    var_dump($obj_numeric_index);
    
    echo $obj_numeric_index->1.;      // no
    echo $obj_numeric_index->'1.';    // no
    echo $obj_numeric_index->{'1.'};  // OK !
    echo $obj_numeric_index->2.;      // no
    echo $obj_numeric_index->'2';     // no
    echo $obj_numeric_index->{'2'};   // no
    echo $obj_numeric_index->3;       // no
    echo $obj_numeric_index->{3};     // no
    echo $obj_numeric_index->{'3'};   // no
    

    Not very practical, I agree.


    Edit. Transform an array to an object, the right way:

    <?php
    $numeric_index_array = array(10, 20, 30) ;
    
    $obj = new StdClass;
    array_walk($numeric_index_array, function(&$val, $key) use (&$obj) {
        $obj->{$key} = $val;
    });
    
    echo $obj->{1}; // OK !
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化