2009-12-11 22 views

Antwort

10

Warum nicht einfach werfen?

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

Wenn es mehrdimensional ist, stellt Richard Castera die folgende Lösung auf 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

Die besten Antworten sind oft die einfachsten +1 – alex

3

Wenn es ein eindimensionales Array ist, sollte ein gegossenes arbeiten:

$obj = (object)$array; 
0

Dies funktioniert für mich

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

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

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

stellen Sie sicher, dass str_replace es als ‚-‘ in Variablennamen in PHP nicht erlaubt ist, sowie:

Regeln für Variablen

* 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) 

So benennen, da diese in Arrays erlaubt sind, wenn Jeder von ihnen kommt im $ Schlüssel aus dem Array, das Sie konvertieren, Sie werden böse Fehler haben.

Verwandte Themen