2009-12-11 65 views

回答

10

爲什麼不只是施放它?

$myObj = (object) array("name" => "Jonathan"); 
print $myObj->name; // Jonathan 

如果它是多維的,理查德Castera提供his blog以下解決方案:

function arrayToObject($array) { 
    if(!is_array($array)) { 
    return $array; 
    } 
    $object = new stdClass(); 
    if (is_array($array) && count($array) > 0) { 
     foreach ($array as $name=>$value) { 
     $name = strtolower(trim($name)); 
      if (!empty($name)) { 
      $object->$name = arrayToObject($value); 
      } 
     } 
     return $object; 
    } else { 
     return FALSE; 
    } 
} 
+0

最佳答案往往是最簡單的+1 – alex 2009-12-11 00:55:47

3

如果它是一個一維數組,鑄造應工作:

$obj = (object)$array; 
0

這適用於我

if (is_array($array)) { 
$obj = new StdClass(); 
foreach ($array as $key => $val){ 

    $key = str_replace("-","_",$key) 

    $obj->$key = $val; 
} 
$array = $obj; 
} 

確保str_replace函數存在爲「 - 」沒有在PHP變量名中允許的,以及:

命名規則變量

* A variable name must start with a letter or an underscore "_" 
* A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _) 
* A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString) 

所以,因爲這些被允許在陣列中,如果它們中的任何一個都來自你正在轉換的數組的$ key,你將會有令人討厭的錯誤。