C'è una function PHP che lo farà automaticamente?
if (is_arrays($arrays)) { $obj = new StdClass(); foreach ($arrays as $key => $val){ $obj->$key = $val; } $arrays = $obj; }
Perché non lo hai appena lanciato?
$myObj = (object) arrays("name" => "Jonathan"); print $myObj->name; // Jonathan
Se è multidimensionale, Richard Castera fornisce la seguente soluzione sul suo blog :
function arraysToObject($arrays) { if(!is_arrays($arrays)) { return $arrays; } $object = new stdClass(); if (is_arrays($arrays) && count($arrays) > 0) { foreach ($arrays as $name=>$value) { $name = strtolower(trim($name)); if (!empty($name)) { $object->$name = arraysToObject($value); } } return $object; } else { return FALSE; } }
Se è un arrays unidimensionale, un cast dovrebbe funzionare:
$obj = (object)$arrays;
Questo funziona per me
if (is_arrays($arrays)) { $obj = new StdClass(); foreach ($arrays as $key => $val){ $key = str_replace("-","_",$key) $obj->$key = $val; } $arrays = $obj; }
assicurati che str_replace sia presente poiché '-' non è consentito all'interno dei nomi di variables in php, così come:
Denominare le regole per le variables
* A variable name must start with a letter or an underscore "_" * A variable name can only contain alpha-numbersc characters and underscores (az, AZ, 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)
Quindi, dal momento che questi sono consentiti negli arrays, se qualcuno di essi arriva nella chiave $ dall'arrays che si sta convertendo, si avranno degli errori brutti.