這篇文章下面寫了一個將陣列轉換成物件的方法, 這個陣列的鍵為數字(即陣列為索引陣列), 存取物件的時候, $obj->1 顯然錯位,那到底該怎麼樣存取物件的數字屬性呢?
$obj->{1} ; 表示的是存取物件 $obj 的屬性的鍵為 1 對應的屬性值!
<?php /** * Created by PhpStorm. * User: FLY.YUAN * Date: 16-6-14 * Time: 下午2:26 */ function toObject($array) { //$o = (object)''; $o = new \stdClass(); foreach ($array as $key => $value) { if (is_array($value)) { $value = toObject($value); } $o->$key = $value; } return $o; } $obj = toObject(array( array(1=>23))); echo "<pre class="brush:php;toolbar:false">"; //JSON encode, and then decode your object passing true as the second param in the decode function. //This will return an associative array. //var_dump(json_decode(json_encode($obj), true)); var_dump($obj->{0}->{1}); $a = array('123' => '123', '123foo' => '123foo'); $o = json_decode(json_encode($a), true); var_dump($o); function recursive_cast_to_array($o) { $a = (array)$o; foreach ($a as &$value) { if (is_object($value)) { $value = recursive_cast_to_array($value); } } return $a; } $myVar = toObject(array('highlighting' => array('448364' => array('Data' => array(123))))); $arr = recursive_cast_to_array($myVar); echo 134; var_dump( $myVar->highlighting->{448364}->Data->{0}); var_dump(NULL == false); $test = array(); $test['$.router'] = 123; var_dump($test);
以上是php 如何存取物件的屬性的詳細內容。更多資訊請關注PHP中文網其他相關文章!