转换为对象索引数组

Fab*_*ora 7 php casting

可能重复:
使用数字键作为对象转换数组

我想知道(object)型铸造.

可以做很多有用的事情,比如将一个关联数组转换为一个对象,一些不那么有用和一些有趣(恕我直言)的东西,比如将标量值转换为对象.

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

// Converting to object an indexed array
$obj = (object) array( 'apple', 'fruit' );
Run Code Online (Sandbox Code Playgroud)

访问特定值怎么样?

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
                     )
                    */
Run Code Online (Sandbox Code Playgroud)

以下工作因为stdClass动态实现CountableArrayAccess:

foreach( $obj as $k => $v ) {
    print $k . ' => ' . $v . PHP_EOL;
}  
Run Code Online (Sandbox Code Playgroud)

Pet*_*ter 4

这实际上是一个报告的错误

它被认为“修复成本太高”,并且该决议已“更新文档以描述这种无用的怪癖,因此现在它是正式的正确行为” [1]

不过,有一些解决方法

由于get_object_vars什么也没有给你,你唯一能做的就是:

  1. 您可以迭代stdClass使用foreach
  2. 您可以将其转换回数组。
  3. 您可以使用 json_decode+json_encode 将其转换为对象(这是肮脏的技巧)

示例 1:

$obj = (object) array( 'apple', 'fruit' );
foreach($obj as $key => $value) { ...
Run Code Online (Sandbox Code Playgroud)

示例2:

$obj = (object) array( 'apple', 'fruit' );
$array = (array) $obj;
echo $array[0];
Run Code Online (Sandbox Code Playgroud)

示例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"}
Run Code Online (Sandbox Code Playgroud)

这就是为什么你不应该将非关联数组转换为对象:)

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

// 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')));
Run Code Online (Sandbox Code Playgroud)

代替

$obj = (Object) array('apple','fruit'); 
Run Code Online (Sandbox Code Playgroud)