Konwertuj obiekt PHP na tablicę asocjacyjną
Integruję API do mojej strony, która działa z danymi przechowywanymi w obiektach, podczas gdy mój kod jest napisany przy użyciu tablic.
Chciałbym, aby szybka i brudna funkcja przekonwertowała obiekt na tablicę.
27 answers
Po prostu wpisz to
$array = (array) $yourObject;
Z http://www.php.net/manual/en/language.types.array.php
Jeśli obiekt zostanie przekonwertowany na tablicę, wynikiem będzie tablica, której elementy są właściwościami obiektu. Klucze są nazwami zmiennych składowych, z kilkoma wyjątkami: właściwości integer są niedostępne; prywatne zmienne mają nazwę klasy poprzedzoną nazwą zmiennej; chronione zmienne mają " * " poprzedzoną nazwą zmiennej. Te preliminarz wartości mają null bajty po obu stronach.
Przykład: Simple Object
$object = new StdClass;
$object->foo = 1;
$object->bar = 2;
var_dump( (array) $object );
wyjście:
array(2) {
'foo' => int(1)
'bar' => int(2)
}
Przykład: Obiekt Złożony
class Foo
{
private $foo;
protected $bar;
public $baz;
public function __construct()
{
$this->foo = 1;
$this->bar = 2;
$this->baz = new StdClass;
}
}
var_dump( (array) new Foo );
wyjście (z \ 0s edytowane dla jasności):
array(3) {
'\0Foo\0foo' => int(1)
'\0*\0bar' => int(2)
'baz' => class stdClass#2 (0) {}
}
wyjście z var_export
zamiast var_dump
:
array (
'' . "\0" . 'Foo' . "\0" . 'foo' => 1,
'' . "\0" . '*' . "\0" . 'bar' => 2,
'baz' =>
stdClass::__set_state(array(
)),
)
Typecasting w ten sposób nie spowoduje głębokiego odlewania wykresu obiektowego i musisz zastosować bajty null (jak wyjaśniono w cytacie podręcznika), aby uzyskać dostęp do dowolnego atrybuty Niepubliczne. Tak więc działa to najlepiej podczas odlewania obiektów StdClass lub obiektów posiadających tylko właściwości publiczne. Na szybko i brudno (o co prosiłeś) jest w porządku.
Zobacz również ten dogłębny wpis na blogu:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-18 16:02:29
Możesz szybko przekonwertować głęboko zagnieżdżone obiekty na tablice asocjacyjne, opierając się na zachowaniu funkcji kodowania/dekodowania JSON:
$array = json_decode(json_encode($nested_object), true);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-19 18:56:23
Od pierwszego trafienia Google dla " php object to assoc array " mamy to:
function object_to_array($data)
{
if (is_array($data) || is_object($data))
{
$result = array();
foreach ($data as $key => $value)
{
$result[$key] = object_to_array($value);
}
return $result;
}
return $data;
}
Źródło w codesnippets.joyent.com .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-19 12:06:17
Jeśli Twoje właściwości obiektu są publiczne, możesz to zrobić:
$array = (array) $object;
Jeśli są prywatne lub chronione, będą miały dziwne nazwy kluczy na tablicy. Tak więc, w tym przypadku będziesz potrzebował następującej funkcji:
function dismount($object) {
$reflectionClass = new ReflectionClass(get_class($object));
$array = array();
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$array[$property->getName()] = $property->getValue($object);
$property->setAccessible(false);
}
return $array;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-23 10:12:37
Wszystkie inne odpowiedzi zamieszczone tutaj działają tylko z atrybutami publicznymi. Oto jedno rozwiązanie, które działa z javabean - podobnymi obiektami używającymi odbicia i getterów:
function entity2array($entity, $recursionDepth = 2) {
$result = array();
$class = new ReflectionClass(get_class($entity));
foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
$methodName = $method->name;
if (strpos($methodName, "get") === 0 && strlen($methodName) > 3) {
$propertyName = lcfirst(substr($methodName, 3));
$value = $method->invoke($entity);
if (is_object($value)) {
if ($recursionDepth > 0) {
$result[$propertyName] = $this->entity2array($value, $recursionDepth - 1);
} else {
$result[$propertyName] = "***"; //stop recursion
}
} else {
$result[$propertyName] = $value;
}
}
}
return $result;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-15 12:22:34
class Test{
const A = 1;
public $b = 'two';
private $c = test::A;
public function __toArray(){
return call_user_func('get_object_vars', $this);
}
}
$my_test = new Test();
var_dump((array)$my_test);
var_dump($my_test->__toArray());
Wyjście
array(2) {
["b"]=>
string(3) "two"
["Testc"]=>
int(1)
}
array(1) {
["b"]=>
string(3) "two"
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-09 02:41:23
Oto jakiś kod:
function object_to_array($data)
{
if ((! is_array($data)) and (! is_object($data))) return 'xxx'; //$data;
$result = array();
$data = (array) $data;
foreach ($data as $key => $value) {
if (is_object($value)) $value = (array) $value;
if (is_array($value))
$result[$key] = object_to_array($value);
else
$result[$key] = $value;
}
return $result;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-20 16:58:37
A co z get_object_vars($obj)
? Wydaje się przydatne, jeśli chcesz uzyskać dostęp tylko do publicznych właściwości obiektu.
http://www.php.net/function.get-object-vars
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-11 14:21:02
Aby przekonwertować obiekt do tablicy wystarczy go jawnie obsadzić
$name_of_array = (array) $name_of_object;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-29 13:14:51
Type cast your object to an array.
$arr = (array) $Obj;
To rozwiąże twój problem.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-22 07:08:49
Cześć,
Oto moja rekurencyjna funkcja PHP do konwersji obiektów PHP na tablicę asocjacyjną
// ---------------------------------------------------------
// ----- object_to_array_recusive --- function (PHP) -------
// ---------------------------------------------------------
// --- arg1: -- $object = PHP Object - required ---
// --- arg2: -- $assoc = TRUE or FALSE - optional ---
// --- arg3: -- $empty = '' (Empty String) - optional ---
// ---------------------------------------------------------
// ----- return: Array from Object --- (associative) -------
// ---------------------------------------------------------
function object_to_array_recusive ( $object, $assoc=TRUE, $empty='' )
{
$res_arr = array();
if (!empty($object)) {
$arrObj = is_object($object) ? get_object_vars($object) : $object;
$i=0;
foreach ($arrObj as $key => $val) {
$akey = ($assoc !== FALSE) ? $key : $i;
if (is_array($val) || is_object($val)) {
$res_arr[$akey] = (empty($val)) ? $empty : object_to_array_recusive($val);
}
else {
$res_arr[$akey] = (empty($val)) ? $empty : (string)$val;
}
$i++;
}
}
return $res_arr;
}
// ---------------------------------------------------------
// ---------------------------------------------------------
Przykład użycia:
// ---- return associative array from object, ... use:
$new_arr1 = object_to_array_recusive($my_object);
// -- or --
// $new_arr1 = object_to_array_recusive($my_object,TRUE);
// -- or --
// $new_arr1 = object_to_array_recusive($my_object,1);
// ---- return numeric array from object, ... use:
$new_arr2 = object_to_array_recusive($my_object,FALSE);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-20 23:03:07
Funkcja niestandardowa do konwersji stdClass do tablicy:
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
} else {
// Return array
return $d;
}
}
Kolejna funkcja do konwersji tablicy na stdClass:
function arrayToObject($d) {
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return (object) array_map(__FUNCTION__, $d);
} else {
// Return object
return $d;
}
}
Przykład Użycia:
// Create new stdClass Object
$init = new stdClass;
// Add some test data
$init->foo = "Test data";
$init->bar = new stdClass;
$init->bar->baaz = "Testing";
$init->bar->fooz = new stdClass;
$init->bar->fooz->baz = "Testing again";
$init->foox = "Just test";
// Convert array to object and then object back to array
$array = objectToArray($init);
$object = arrayToObject($array);
// Print objects and array
print_r($init);
echo "\n";
print_r($array);
echo "\n";
print_r($object);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-25 19:32:55
Możesz również utworzyć funkcję w PHP do konwersji tablicy obiektów.
function object_to_array($object) {
return (array) $object;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-27 09:51:18
Możesz to zrobić, gdy uzyskasz dane jako obiekty z baz danych -- >
// Suppose result is the end product from some query $query
$result = $mysqli->query($query);
$result = db_result_to_array($result);
function db_result_to_array($result)
{
$res_array = array();
for ($count=0; $row = $result->fetch_assoc(); $count++)
$res_array[$count] = $row;
return $res_array;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-17 22:43:38
function readObject($object) {
$name = get_class ($object);
$name = str_replace('\\', "\\\\", $name); \\ Comment this line, if you dont use class namespaces approach in your project
$raw = (array)$object;
$attributes = array();
foreach ($raw as $attr => $val) {
$attributes[preg_replace('('.$name.'|\*|)', '', $attr)] = $val;
}
return $attributes;
}
Zwraca tablicę bez znaków specjalnych i nazw klas
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-12 19:24:00
Po pierwsze, jeśli potrzebujesz tablicy z obiektu, prawdopodobnie powinieneś najpierw utworzyć dane jako tablicę. Pomyśl o tym.
Nie używaj instrukcji foreach ani przekształceń JSON. Jeśli planujesz to, ponownie pracujesz ze strukturą danych, a nie z obiektem.
Jeśli naprawdę tego potrzebujesz, użyj podejścia zorientowanego obiektowo, aby mieć czysty i maintable kod. Na przykład:
Obiekt jako tablica
class PersonArray implements \ArrayAccess, \IteratorAggregate
{
public function __construct(Person $person) {
$this->person = $person;
}
// ...
}
Jeśli potrzebujesz wszystkich właściwości użyj obiektu transfer
class PersonTransferObject
{
private $person;
public function __construct(Person $person) {
$this->person = $person;
}
public function toArray() {
return [
// 'name' => $this->person->getName();
];
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-27 09:38:46
Ta funkcja może konwertować obiekt proprity na Array associatif
function ObjetToArray($adminBar){
$reflector = new ReflectionObject($adminBar);
$nodes = $reflector->getProperties();
$out=[];
foreach ($nodes as $node) {
$nod=$reflector->getProperty($node->getName());
$nod->setAccessible(true);
$out[$node->getName()]=$nod->getValue($adminBar);
}
return $out;
}
Użyj > = php5
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-01 13:43:55
Konwertowanie i usuwanie irytujących gwiazd:
$array = (array) $object;
foreach($array as $key => $val)
{
$new_array[str_replace('*_','',$key)] = $val;
}
Prawdopodobnie będzie to tańsze niż używanie odbić.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-03 08:54:15
Niektóre impovements do" dobrze znany " kod
/*** mixed Obj2Array(mixed Obj)***************************************/
static public function Obj2Array($_Obj) {
if (is_object($_Obj))
$_Obj = get_object_vars($_Obj);
return(is_array($_Obj) ? array_map(__METHOD__, $_Obj) : $_Obj);
} // BW_Conv::Obj2Array
Zauważ, że jeśli funkcja jest członkiem klasy (jak wyżej) musisz zmienić __FUNCTION__
na __METHOD__
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-24 13:23:35
Możesz również użyć komponentu Symfony Serializer
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
$array = json_decode($serializer->serialize($object, 'json'), true);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-26 11:55:04
$Menu = new Admin_Model_DbTable_Menu();
$row = $Menu->fetchRow($Menu->select()->where('id = ?', $id));
$Addmenu = new Admin_Form_Addmenu();
$Addmenu->populate($row->toArray());
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-07 10:11:14
Tutaj stworzyłem metodę objectToArray () , która działa również z obiektami rekurencyjnymi, np. gdy $objectA
zawiera $objectB
, co wskazuje ponownie na $objectA
.
Dodatkowo ograniczyłem wyjście do właściwości publicznych używając ReflectionClass. Pozbądź się go, jeśli nie potrzebujesz.
/**
* Converts given object to array, recursively.
* Just outputs public properties.
*
* @param object|array $object
* @return array|string
*/
protected function objectToArray($object) {
if (in_array($object, $this->usedObjects, TRUE)) {
return '**recursive**';
}
if (is_array($object) || is_object($object)) {
if (is_object($object)) {
$this->usedObjects[] = $object;
}
$result = array();
$reflectorClass = new \ReflectionClass(get_class($this));
foreach ($object as $key => $value) {
if ($reflectorClass->hasProperty($key) && $reflectorClass->getProperty($key)->isPublic()) {
$result[$key] = $this->objectToArray($value);
}
}
return $result;
}
return $object;
}
Aby zidentyfikować już używane obiekty, używam chronionej właściwości w tej (abstrakcyjnej) klasie o nazwie $this->usedObjects
. Jeśli zostanie znaleziony rekurencyjnie zagnieżdżony obiekt, zostanie on zastąpiony przez łańcuch **recursive**
. W przeciwnym razie zawiedzie z powodu nieskończonej pętli.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-15 00:31:21
Ta odpowiedź jest tylko połączeniem różnych odpowiedzi tego postu, ale rozwiązaniem jest konwersja obiektu PHP o publicznych lub prywatnych właściwościach z prostymi wartościami lub tablicami w tablicy asocjacyjnej ...
function object_to_array($obj)
{
if (is_object($obj)) $obj = (array)$this->dismount($obj);
if (is_array($obj)) {
$new = array();
foreach ($obj as $key => $val) {
$new[$key] = $this->object_to_array($val);
}
} else $new = $obj;
return $new;
}
function dismount($object)
{
$reflectionClass = new \ReflectionClass(get_class($object));
$array = array();
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$array[$property->getName()] = $property->getValue($object);
$property->setAccessible(false);
}
return $array;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-08 15:48:29
Krótkie rozwiązanie @SpYk3HH
function objectToArray($o)
{
$a = array();
foreach ($o as $k => $v)
$a[$k] = (is_array($v) || is_object($v)) ? objectToArray($v): $v;
return $a;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-25 12:17:40
Za pomocą typecasting można rozwiązać swój problem. Po prostu dodaj następujące linie do zwracanego obiektu:
$arrObj = array(yourReturnedObject);
Możesz również dodać do niego nowy klucz i parę wartości używając:
$arrObj['key'] = value;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-20 09:54:07
Ponieważ wiele osób znajduje Ten wątek z powodu problemów z dynamicznym dostępem do atrybutów obiektu, zaznaczę tylko, że możesz to zrobić w php: $valueRow->{"valueName"}
In Context (removed HTML output for readability):
$valueRows = json_decode("{...}"); // rows of unordered values decoded from a json-object
foreach($valueRows as $valueRow){
foreach($references as $reference){
if(isset($valueRow->{$reference->valueName})){
$tableHtml .= $valueRow->{$reference->valueName};
}else{
$tableHtml .= " ";
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-22 05:56:36
Oto moja propozycja, jeśli masz obiekty w obiektach z nawet prywatnymi członkami:
public function dismount($object) {
$reflectionClass = new \ReflectionClass(get_class($object));
$array = array();
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
if (is_object($property->getValue($object))) {
$array[$property->getName()] = $this->dismount($property->getValue($object));
} else {
$array[$property->getName()] = $property->getValue($object);
}
$property->setAccessible(false);
}
return $array;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-22 12:52:59