lau*_*kok 5 php arrays object php-5.3
如何访问已转换为对象的数组的属性/值?例如,我想访问索引0中的值,
$obj = (object) array('qualitypoint', 'technologies', 'India');
var_dump($obj->0);
Run Code Online (Sandbox Code Playgroud)
错误,
解析错误:语法错误,意外T_LNUMBER,期待T_STRING或T_VARIABLE或C中的'{'或'$':...第11行的conversion_to_object.php
您无法通过$obj->0其访问值的原因是它反对 PHP 变量命名,请参阅http://php.net/manual/en/language.variables.basics.php了解更多信息。即使你使用ArrayObject你仍然会遇到同样的问题
但是有一个补丁...您可以将所有整数键转换为字符串或编写自己的转换函数
例子
$array = array('qualitypoint', 'technologies', 'India' , array("hello","world"));
$obj = (object) $array;
$obj2 = arrayObject($array);
function arrayObject($array)
{
$object = new stdClass();
foreach($array as $key => $value)
{
$key = (string) $key ;
$object->$key = is_array($value) ? arrayObject($value) : $value ;
}
return $object ;
}
var_dump($obj2->{0}); // Sample Output
var_dump($obj,$obj2); // Full Output to see the difference
$sumObject = $obj2->{3} ; /// Get Sub Object
var_dump($sumObject->{1}); // Output world
Run Code Online (Sandbox Code Playgroud)
输出
string 'qualitypoint' (length=12)
Run Code Online (Sandbox Code Playgroud)
满输出
object(stdClass)[1]
string 'qualitypoint' (length=12)
string 'technologies' (length=12)
string 'India' (length=5)
array
0 => string 'hello' (length=5)
1 => string 'world' (length=5)
object(stdClass)[2]
public '0' => string 'qualitypoint' (length=12)
public '1' => string 'technologies' (length=12)
public '2' => string 'India' (length=5)
public '3' =>
object(stdClass)[3]
public '0' => string 'hello' (length=5)
public '1' => string 'world' (length=5)
Run Code Online (Sandbox Code Playgroud)
多阵列输出
谢谢
:)
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |