转换为对象索引数组

时间:2012-09-01 14:16:52

标签: php casting

  

可能重复:
  Casting an Array with Numeric Keys as an Object

我想知道(object)类型转换。

可以做很多有用的事情,比如将一个关联数组转换为一个对象,还有一些不那么有用,有点滑稽(恕我直言)的东西,比如converting a scalar value to object

但是如何访问索引数组的转换结果?

// Converting to object an indexed array
$obj = (object) array( 'apple', 'fruit' );

访问特定值怎么样?

print $obj[0];      // Fatal error & doesn't have and any sense
print $obj->scalar[0];  // Any sense
print $obj->0;      // Syntax error
print $obj->${'0'};     // Fatal error: empty property.   
print_r( get_object_vars( $obj ) ); // Returns Array()

print_r( $obj );    /* Returns
                    stdClass Object
                     (
                            [0] => apple
                            [1] => fruit
                     )
                    */

以下是有效的,因为stdClass动态实现CountableArrayAccess

foreach( $obj as $k => $v ) {
    print $k . ' => ' . $v . PHP_EOL;
}  

1 个答案:

答案 0 :(得分:3)

这实际上是reported bug

  

它被认为“太难以修复”并且解决方案已经解决了   已经“更新了文档来描述这个无用的怪癖,所以它   现在是正式的正确行为“[1]

但是,有一些变通办法

由于get_object_vars没有给你任何东西,你唯一能做的就是:

  1. 您可以使用stdClass
  2. foreach进行迭代
  3. 您可以将其转换为数组。
  4. 您可以使用json_decode + json_encode将其转换为对象(这是一个肮脏的技巧)
  5. 示例1。:

    $obj = (object) array( 'apple', 'fruit' );
    foreach($obj as $key => $value) { ...
    

    示例2。:

    $obj = (object) array( 'apple', 'fruit' );
    $array = (array) $obj;
    echo $array[0];
    

    示例3。:

    $obj = (object) array( 'apple', 'fruit' );    
    $obj = json_decode(json_encode($obj));    
    echo $obj->{'0'};
    var_dump(get_object_vars($obj)); // array(2) {[0]=>string(5) "apple"[1]=>string(5)"fruit"}
    

    这就是为什么你不应该把非关联数组作为对象:)

    但如果你愿意,可以这样做:

    // PHP 5.3.0 and higher
    $obj = json_decode(json_encode(array('apple', 'fruit'), JSON_FORCE_OBJECT));
    // PHP 5 >= 5.2.0
    $obj = json_decode(json_encode((Object) array('apple', 'fruit')));
    

    而不是

    $obj = (Object) array('apple','fruit'); 
    
相关问题