How to convert an array to object in PHP?
This one worked for me
function array_to_obj($array, &$obj)
{
foreach ($array as $key => $value)
{
if (is_array($value))
{
$obj->$key = new stdClass();
array_to_obj($value, $obj->$key);
}
else
{
$obj->$key = $value;
}
}
return $obj;
}
function arrayToObject($array)
{
$object= new stdClass();
return array_to_obj($array,$object);
}
usage :
$myobject = arrayToObject($array);
print_r($myobject);
returns :
[127] => stdClass Object
(
[status] => Have you ever created a really great looking website design
)
[128] => stdClass Object
(
[status] => Figure A.
Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution.
)
[129] => stdClass Object
(
[status] => The other day at work, I had some spare time
)
like usual you can loop it like:
foreach($myobject as $obj)
{
echo $obj->status;
}
How to convert an array into an object using stdClass()
You just add this code
$clasa = (object) array(
'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
);
If you want to see is this stdClass object just call this
print_r($clasa);
If you want to convert an array to object code will be
$arr = array('a'=>'apple','b'=>'ball');
$arr = (object) $arr;
You don't need to use stdClass. It will automatically converted to stdClass
PHP convert Array to Object
If you want to access your "metafields's id" like $response->metafields[13][id]
then you need to cast your response array to object.
Ex.
$response = (object) array(
'metafields' => array(
'13' => (object) array(
'id' => 32616923206,
'namespace' => "ly26638"
)
)
);
Then you can use syntax like $response->metafields[13]->id
to access the "id" value.
Converting array to objects in PHP
You have a multidimensinal array there. By calling $cars = (object) $cars;
you basically create the following object:
$cars = {
'0' => [
'make' => 'Audi',
'model' => 'A4',
'year' => '2014'
],
'1' => [
'make' => 'Benz',
'model' => 'c300',
'year' => '2015'
],
'2' => [
'make' => 'BMW',
'model' => 'i8',
'year' => '2016'
]
};
The inner arrays are still arrays. What you want to do isntead is transforming your inner arrays to objects, while letting your outer array be an array. This can be done with the function array_map
:
$cars = array_map(function($array){
return (object)$array;
}, $cars);
This will create your desired output.
$cars = [
{
'make' => 'Audi',
'model' => 'A4',
'year' => '2014'
},
{
'make' => 'Benz',
'model' => 'c300',
'year' => '2015'
},
{
'make' => 'BMW',
'model' => 'i8',
'year' => '2016'
}
];
How to convert array of arrays into object in PHP?
i improvised another way to do so:
$ar=[
'a'=>[
'field1'=>52,
'field2'=>52,
'field3'=>52,
],
'b'=>[
'field1'=>52,
'field2'=>52,
'field3'=>52,
]
];
function ToObj($data) {
if (gettype($data) == 'array')
return (object)array_map("ToObj", $data);
else
return $data;
}
$ObjectResult = array_map("ToObj", $ar);
Convert an array into string or object
I managed to reproduce your "Array to string conversion" error when using the implode
command by running the following line of code:
implode(";", [[]]); // PHP Notice: Array to string conversion in php shell code on line 1
For converting a nested array into a string I found that a foreach
loop worked:
$nestedArray = ['outerKeyOne' => ['innerKeyOne' => 'valueOne'], 'outerKeyTwo' => ['innerKeyTwo' => 'valueTwo']];
$arrayOfStrings = [];
foreach ($nestedArray as $key => $value) {
$arrayOfStrings[] = implode(",", $value);
}
implode(";", $arrayOfStrings); // string(17) "valueOne;valueTwo"
The second error associated with the line $val = (object) $list;
is from trying to embed an object into the $sql
string. It seems like an object is not what you want here, unless it is an object that has a __toString()
method implemented.
I hope this is of some help. Using var_dump
or something similar would provide more debug output to better diagnose the problems along with the above error messages. That's how I came up with the above code.
How to convert an array into an object using stdClass()
You just add this code
$clasa = (object) array(
'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
);
If you want to see is this stdClass object just call this
print_r($clasa);
If you want to convert an array to object code will be
$arr = array('a'=>'apple','b'=>'ball');
$arr = (object) $arr;
You don't need to use stdClass. It will automatically converted to stdClass
Convert Array to Object
ECMAScript 6 introduces the easily polyfillable Object.assign
:
The
Object.assign()
method is used to copy the values of all
enumerable own properties from one or more source objects to a target
object. It will return the target object.
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
The own length
property of the array is not copied because it isn't enumerable.
Also, you can use ES8 spread syntax on objects to achieve the same result:
{ ...['a', 'b', 'c'] }
For custom keys you can use reduce:
['a', 'b', 'c'].reduce((a, v) => ({ ...a, [v]: v}), {})
// { a: "a", b: "b", c: "c" }
Related Topics
How to Change the Session Timeout in PHP
How to Implement an Access Control List in My Web MVC Application
How to Replace Certain Parts of My String
How to Create Custom Helper Functions in Laravel
Use PHP to Create, Edit and Delete Crontab Jobs
How to Use Ajax in a Wordpress Shortcode
Comparing String to Integer Gives Strange Results
Slowness Found When Base 64 Image Select and Encode from Database
Convert a PHP Script into a Stand-Alone Windows Executable
Extract a Single (Unsigned) Integer from a String
Pdoexception Sqlstate[Hy000] [2002] No Such File or Directory
File_Get_Contents(): Ssl Operation Failed With Code 1, Failed to Enable Crypto
MySQL and PHP: Utf-8 With Cyrillic Characters
How to Implement a Good Profanity Filter
How to Truncate a String in PHP to the Word Closest to a Certain Number of Characters