PHP get keys from array in object - php

I've got object and I need list of it's keys.
for now I doing that in foreach
foreach($obj as $key => $attribute){
var_dump($key);
}
Is there some PHP built in function for getting object keys like array_keys for arrays?
trace
object(Solarium\QueryType\Select\Result\Document)#1383 (1) {
["fields":protected]=> array(31) { ["pdf_url"]=> string(51)
"xxxxxxxxxxxx" ["title"]=>
string(150) ......

class A
{
private $a = 1;
protected $b = 2;
public $c = 3;
}
$object = new A();
$fields = get_object_vars($object);
But by this method, you can only get public fields from your object,
i.e
print_r($fields);
Will output
Array ( [c] => 3 )

Problem is because it was
array in object.
I solve problem with this
array_keys($obj->getFields())

Related

Apply multidimension array data to an object

For a given PHP object (loaded from CouchDB) $obj:
class stdClass#1 (3) {
public $_id =>
string(10) "nochecksum"
public $_rev =>
string(34) "1-4f734a24465bf7ba2de316fe87ffa0c1"
public $rooms =>
class stdClass#2 (1) {
public $kitchen =>
class stdClass#3 (1) {
public $ceilingFan =>
bool(false)
}
}
}
And for a given multidimensional array of data $arr, consisting of changed or new values for properties:
array(1) {
'rooms' =>
array(1) {
'kitchen' =>
array(1) {
'needsCleaning' =>
bool(true)
}
}
}
How is it possible to set $obj's properties to be values from $arr?
The solution is simple for a single dimension array:
foreach ($arr as $k=>$v) {
$obj->{$k}=$v;
}
I tried with a recursive function, but I don't know how to reference the parent(s):
$obj = setObjectFromArray($obj, $arr);
function setObjectFromArray($obj, $arr, $tree=Array())
{
foreach ($arr as $k=>$v) {
if (is_array($v)) {
$tree[]=$k;
$obj = setObjectFromArray($obj, $v, $tree);
} else {
// Here $tree is Array('rooms','kitchen')
// I want to set $obj->rooms->kitchen->{$k}
}
}
return $obj;
}
I think passing a reference of the object's property to the recursive function might work - but I don't understand either enough to make an educated guess. Any help appreciated
You could do it like this:
function setObjectFromArray($obj, $arr) {
foreach ($arr as $k => $v) {
$obj->{$k} = is_array($v) ? setObjectFromArray($obj->{$k}, $v) : $v;
}
return $obj;
}
The major difference with your code is the assignment to $obj->{$k} instead of $obj: that way you rewrite (or create) the property at each level of the recursion tree.
Be aware that even if you call the function like this:
$result = setObjectFromArray($obj, $arr);
... $obj will still have been modified and be equal to $result.
This solution is not totally obvious and maybe can fail somewhere but still - it's pair of json functions:
$r = array(
'rooms' => array(
'kitchen' => array(
'needsCleaning' => true
)
)
);
echo '<pre>',print_r(json_decode(json_encode($r))), '</pre>';
Explanation: you encode array to json-string and then decode this string to object.
Maybe you can expand this code further.

Can I set the keys of an array using array functions like array_map

I really like the functional programming style of using array map to create an array of objects from another array of objects.
$newObjects = array_map(
function($oldObject) {
return new NewObject($oldObject);
},
$oldObjects
);
Which all works fine but I would really like to be able to set the indices of the array so that they are the ids of the original objects for easier search and retrieval from the array but I cannot think how to do it other then which is not as elegant.
$newObjects = array();
foreach ($oldObjects as $oldObject) {
$newObjects[$oldObject->getId()] = new NewObject($oldObject);
}
Is there a way I can do this?
That is - array_reduce() is exactly what you need:
class Bar
{
protected $id;
public function __construct($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
}
class Foo
{
protected $bar;
public function __construct(Bar $bar)
{
$this->bar = $bar;
}
}
$oldObjects = [new Bar('x'), new Bar('y'), new Bar('z')];
$newObjects = array_reduce($oldObjects, function($current, Bar $obj) {
$current[$obj->getId()] = new Foo($obj);
return $current;
}, []);
This will do all in-place without having to spend memory on additional arrays like for array_combine()
However, I would suggest to use such constructs when they're necessary. Using this just because it "looks better" might be not a good idea - as plain loops are in most cases just more readable.
What if you use array_walk and a temporary array with your new indices.
$array = ['A', 'B', 'C', 'D'];
$reIndexedTemp = [];
array_walk(
$array,
function ($item, $key) use (&$reIndexedTemp) {
// here you can have your logic to assemble your new index
$reIndexedTemp[$key + 100] = $item;
}
);
//$array = $reIndexedTemp;
var_dump($array, $reIndexedTemp);
output (without the commented line) :
array(4) {
[0] =>
string(1) "A"
[1] =>
string(1) "B"
[2] =>
string(1) "C"
[3] =>
string(1) "D"
}
array(4) {
[100] =>
string(1) "A"
[101] =>
string(1) "B"
[102] =>
string(1) "C"
[103] =>
string(1) "D"
}
I think a foreach is probably the most readable solution in this case, but you can use array_map() with array_combine() to achieve what you want. Something like:
// empty array to store the old object ids
$ids = [];
// map over old objects, inheriting $id
// from parent scope by reference
$objs = array_map(function($oldObject) use (&$ids) {
$ids[] = $oldObject->getId();
return new NewObject($oldObject);
}, $oldObjects);
// combine id and object arrays
$newObjects = array_combine($ids, $objs);
Hope this helps :)
Looking around - Looking for array_map equivalent to work on keys in associative arrays
Suggests it might work using array_combine
So I guess it would be
$newObjects = array_combine(
array_map(
function($oldObject) {
return $oldObject->getId();
},
$oldObjects
),
array_map(
function($oldObject) {
return new NewObject($oldObject);
},
$oldObjects
)
);
Hmm probably the best, just this side of overblown but definately a lot more complex than the foreach

Convert multidimensional objects to array [duplicate]

This question already has answers here:
Convert a PHP object to an associative array
(33 answers)
Closed 6 months ago.
I'm using amazon product advertising api. Values are returned as a multidimensional objects.
It looks like this:
object(AmazonProduct_Result)#222 (5) {
["_code":protected]=>
int(200)
["_data":protected]=>
string(16538)
array(2) {
["IsValid"]=>
string(4) "True"
["Items"]=>
array(1) {
[0]=>
object(AmazonProduct_Item)#19 (1) {
["_values":protected]=>
array(11) {
["ASIN"]=>
string(10) "B005HNF01O"
["ParentASIN"]=>
string(10) "B008RKEIZ8"
["DetailPageURL"]=>
string(120) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/B005HNF01O?SubscriptionId=AKIAJNFRQCIJLTY6LDTA&tag=*********-20"
["ItemLinks"]=>
array(7) {
[0]=>
object(AmazonProduct_ItemLink)#18 (1) {
["_values":protected]=>
array(2) {
["Description"]=>
string(17) "Technical Details"
["URL"]=>
string(217) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/tech-data/B005HNF01O%3FSubscriptionId%3DAKIAJNFRQCIJLTY6LDTA%26tag%*******-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB005HNF01O"
}
}
[1]=>
object(AmazonProduct_ItemLink)#17 (1) {
["_values":protected]=>
array(2) {
I mean it also has array inside objects. I would like to convert all of them into a multidimensional array.
I know this is old but you could try the following piece of code:
$array = json_decode(json_encode($object), true);
where $object is the response of the API.
You can use recursive function like below:
function object_to_array($obj, &$arr)
{
if (!is_object($obj) && !is_array($obj))
{
$arr = $obj;
return $arr;
}
foreach ($obj as $key => $value)
{
if (!empty($value))
{
$arr[$key] = array();
objToArray($value, $arr[$key]);
}
else {$arr[$key] = $value;}
}
return $arr;
}
function convertObjectToArray($data) {
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($data)) {
return array_map(__FUNCTION__, $data);
}
return $data;
}
Credit to Kevin Op den Kamp.
I wrote a function that does the job, and also converts all json strings to arrays too. This works pretty fine for me.
function is_json($string) {
// php 5.3 or newer needed;
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
function objectToArray($objectOrArray) {
// if is_json -> decode :
if (is_string($objectOrArray) && is_json($objectOrArray)) $objectOrArray = json_decode($objectOrArray);
// if object -> convert to array :
if (is_object($objectOrArray)) $objectOrArray = (array) $objectOrArray;
// if not array -> just return it (probably string or number) :
if (!is_array($objectOrArray)) return $objectOrArray;
// if empty array -> return [] :
if (count($objectOrArray) == 0) return [];
// repeat tasks for each item :
$output = [];
foreach ($objectOrArray as $key => $o_a) {
$output[$key] = objectToArray($o_a);
}
return $output;
}
This is an old question, but I recently ran into this and came up with my own solution.
array_walk_recursive($array, function(&$item){
if(is_object($item)) $item = (array)$item;
});
Now if $array is an object itself you can just cast it to an array before putting it in array_walk_recursive:
$array = (array)$object;
array_walk_recursive($array, function(&$item){
if(is_object($item)) $item = (array)$item;
});
And the mini-example:
array_walk_recursive($array,function(&$item){if(is_object($item))$item=(array)$item;});
In my case I had an array of stdClass objects from a 3rd party source that had a field/property whose value I needed to use as a reference to find its containing stdClass so I could access other data in that element. Basically comparing nested keys in 2 data sets.
I have to do this many times, so I didn't want to foreach over it for each item I need to find. The solution to that issue is usually array_column, but that doesn't work on objects. So I did the above first.
Just in case you came here as I did and didn't find the right answer for your situation, this modified version of one of the previous answers is what ended up working for me:
protected function objToArray($obj)
{
// Not an object or array
if (!is_object($obj) && !is_array($obj)) {
return $obj;
}
// Parse array
foreach ($obj as $key => $value) {
$arr[$key] = $this->objToArray($value);
}
// Return parsed array
return $arr;
}
The original value is a JSON string. The method call looks like this:
$array = $this->objToArray(json_decode($json, true));

return objects on the fly in php

I know this can be done in javascript like so:
function doSomething(){
var something, something_else, another_thing;
// do something with these vars
return {
attribute1 : something,
array1 : [
something_else,
another_thing
]
}
}
can it be done in php?
You can create a new object of stdClass(), assign its attributes and return it.
$x = new stdClass();
$x->attribute1 = "something";
$x->array1 = array(1,2,3);
var_dump($x);
return $x;
PHP does not support object literals. However, it does have a generic stdClass class, which you can typecast an array into for a somewhat similar syntax.
function doSomething()
{
$something = 1;
$something_else = 2;
$another_thing = 3;
return (object) [
"attribute1" => $something,
"array1" => [
$something_else,
$another_thing
]
];
}
var_dump(doSomething());
will give (demo)
object(stdClass)#1 (2) {
["attribute1"]=> int(1)
["array1"]=> array(2) {
[0]=> int(2)
[1]=> int(3)
}
}
Note that you can only use short array syntax as of PHP 5.4. Before that you'd use array().

Convert an Object to an Array

I am working with WordPress and since I don't believe it is possible to sort object details, I was wondering how to go about converting my Object to an Array, so that sorting can be possible.
Any help or guidance would be greatly appreciated.
I am using the WP function get_categories();
The complete content of $category is:
$category->term_id
$category->name
$category->slug
$category->term_group
$category->term_taxonomy_id
$category->taxonomy
$category->description
$category->parent
$category->count
$category->cat_ID
$category->category_count
$category->category_description
$category->cat_name
$category->category_nicename
$category->category_parent
$array = json_decode(json_encode($object), true);
If the object is not too complex (in terms of nesting) you can cast the class to an array:
$example = new StdClass();
$example->foo = 'bar';
var_dump((array) $example);
outputs:
array(1) { ["foo"]=> string(3) "bar" }
However this will only convert the base level. If you have nested objects such as
$example = new StdClass();
$example->foo = 'bar';
$example->bar = new StdClass();
$example->bar->blah = 'some value';
var_dump((array) $example);
Then only the base object will be cast to an array.
array(2) {
["foo"]=> string(3) "bar"
["bar"]=> object(stdClass)#2 (1) {
["blah"]=> string(10) "some value"
}
}
In order to go deeper, you would have to use recursion. There is a good example of an object to array conversion here.
as simple as
$array = (array)$object;
http://www.php.net/manual/en/language.types.array.php#language.types.array.casting
To convert an object to array you can use get_object_vars() (PHP manual):
$categoryVars = get_object_vars($category)
To add to #galen
<?php
$categories = get_categories();
$array = (array)$categories;
?>
To convert the entire object and all it's properties to arrays, you can use this clunky function I've had kicking around for a while:
function object_to_array($object)
{
if (is_array($object) OR is_object($object))
{
$result = array();
foreach($object as $key => $value)
{
$result[$key] = object_to_array($value);
}
return $result;
}
return $object;
}
Demo: http://codepad.org/Tr8rktjN
But for your example, with that data, you should be able to just cast to array as others have already said.
$array = (array) $object;
A less clunky way might be:
function objectToArray($object)
{
if(!is_object( $object ) && !is_array( $object ))
{
return $object;
}
if(is_object($object) )
{
$object = get_object_vars( $object );
}
return array_map('objectToArray', $object );
}
(Sourced from http://www.sitepoint.com/forums/showthread.php?438748-convert-object-to-array)
Note, if you'd like this as a method in a class, change the last line to:
return array_map(array($this, __FUNCTION__), $object );

Categories