How to convert an object properties into an array in php - php

Those data in $data variable. When I'm using dd($data); I got this:
CurlHandle {#1918 ▼
+url: "https://example.com"
+content_type: "application/json; charset=UTF-8"
+http_code: 200
+header_size: 887
+namelookup_time_us: 139522
+pretransfer_time_us: 326662
+redirect_time_us: 0
+starttransfer_time_us: 668686
+total_time_us: 668752
}
I want to convert this data to an array.
I'm using this: $arr = json_decode($data,true);
But, this is not working. Now, how can I convert this?

You can use below solution
$yourArray = json_decode(json_encode($yourObject), true);
and this convert object to an array for more info

Objects are, in PHP, maybe iterable. Notice, you may iterate through an object's public fields only via the foreach loop. So the following works:
$array = [];
foreach ($object as $property) {
$array[] = $property; // Stores public field only
}
var_dump($array);
Simply to get an array of object properties, you may use the get_object_vars() function.
var_dump(get_object_vars($object));
You may cast an object to be an array as #MoussabKbeisy said. And this would be the easiest way:
$array = (array) $object;
Here is another way is using ArrayIterator:
$iterator = new ArrayIterator($object);
var_dump(iterator_to_array($iterator));

while this is a PHP Object so you can deal with it by 2 ways:
1- if you want to get on of it's parameters, you can simply use
$yourObject->parameter;
2- if you need to use convert and use it as array, then there is different ways to convert an object to an array in PHP
//1
$array = (array) $yourObject;
//2
$array = json_decode(json_encode($yourObject), true);
Also see this in-depth blog post:
Fast PHP Object to Array conversion

Related

Convert array of objects with keys to keyed array

I have an array of objects that are defined as {'preference name',value}. For example
$preferences[] = {'abc',123};
$preferences[] = {'def',456};
I'd like to access them like this:
$pref = $preferences['abc'];
Of course, I know I could assign them as a keyed array to begin with, however I'm getting the values via JSON, and json_decode always creates an array of objects. Some example JSON that leads us to the situation above would be:
{'abc':123,'def':456}
Obviously it's trivial to covert these using a loop, but I wondered if there was a better one-liner that might do the job?
If you decode the JSON into associative arrays AND all properties are unique, then just merge the sub arrays:
$preferences = json_decode($json, true);
$preferences = call_user_func_array('array_merge', $preferences);
Seems ugly, but hey, it works.
<?php
$a = ['abc'=>123,'def'=>456];
$obj = json_decode(json_encode($a));
var_dump($obj->abc); //123
$arr = (array)$obj;
var_dump($arr["abc"]); //123

Object of class stdClass could not be converted to string - laravel

I am following this documentation
to implement export to Excel in my laravel 4 project.
So am trying to generate excel file from array like this:
//$results is taken with db query
$data = array();
foreach ($results as $result) {
$result->filed1 = 'some modification';
$result->filed2 = 'some modification2';
$data[] = $result;
}
Excel::create('Filename', function($excel) use($data) {
$excel->sheet('Sheetname', function($sheet) use($data) {
$sheet->fromArray($data);
});
})->export('xls');
But this raises exception:
Object of class stdClass could not be converted to string
What am I doing wrong ?
UPDATE:
Tried this:
$data = get_object_vars($data);
which results in:
get_object_vars() expects parameter 1 to be object, array given
This:
$data = (array)$data;
Results in the initial error.
Try this simple in one line of code:-
$data= json_decode( json_encode($data), true);
Hope it helps :)
$data is indeed an array, but it's made up of objects.
Convert its content to array before creating it:
$data = array();
foreach ($results as $result) {
$result->filed1 = 'some modification';
$result->filed2 = 'some modification2';
$data[] = (array)$result;
#or first convert it and then change its properties using
#an array syntax, it's up to you
}
Excel::create(....
You might need to change your object to an array first. I dont know what export does, but I assume its expecting an array.
You can either use
get_object_vars()
Or if its a simple object, you can just typecast it.
$arr = (array) $Object;
If you have a Collection of stdClass objects, you could try with this:
$data = $data->map(function ($item){
return get_object_vars($item);
});
I was recieving the same error when I was tring to call an object element by using another objects return value like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->$this->array1->country;// Error line
The above code was throwing the error and I tried many ways to fix it like; calling this part $this->array1->country in another function as return value, (string), taking it into quotations etc. I couldn't even find the solution on the web then i realised that the solution was very simple. All you have to do it wrap it with curly brackets and that allows you to target an object with another object's element value. like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->{$this->array1->country};
If anyone facing the same and couldn't find the answer, I hope this can help because i spend a night for this simple solution =)
This is easy all you need to do is something like this Grab your contents like this
$result->get(filed1) = 'some modification';
$result->get(filed2) = 'some modification2';

Fetching an object in Mongo PHP library

I use this MongoDB library for PHP
If I use this code:
$db->users->find();
I get an associative array.
Is it possible to get an object as a result of find() method?
For example, in PDO I can do it like this:
$stmt->fetch(PDO::FETCH_OBJ);
Thank you.
If all you're looking for is an stdclass object (like with PDO::FETCH_OBJ), you can cast the current element:
$obj = (object) $db->users->find()->getNext();
Learn more about casting in the PHP manual:
Type Juggling (PHP Manual)
The call
$db->users->find();
returns a \MongoCursor object, which is an iterator you can loop over in a foreach loop as you would with an array. But each result you get from it, though, is an associative array.
http://php.net/mongocollection.find
So, to get objects instead you could cast each item to object prior to using it :
$list = $db->users->find();
foreach($list as $user) {
$user = (object)$user; // object cast here
echo $user->name; // use it as an object
}

How to convert a JSON string into an array (PHP)?

using the below code for decoding json
$categories = json_decode($data);
$categories = $categories->data;
where i get this
{"categories":[{"id":1,"name":"Utilities","apps":897,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/uti.jpg"},{"id":2,"name":"Productivity","apps":477,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/pro.jpg"},{"id":3,"name":"Music","apps":466,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/mus.jpg"},{"id":4,"name":"Travel","apps":289,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/tra.jpg"},{"id":5,"name":"Navigation","apps":297,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/nav.jpg"},{"id":6,"name":"Books","apps":271,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/boo.jpg"},{"id":7,"name":"Healthcare & Fitness","apps":250,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/hea.jpg"},{"id":8,"name":"Games","apps":5116,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/gam.jpg"},{"id":9,"name":"Social Networking","apps":272,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/soc.jpg"},{"id":10,"name":"Lifestyle","apps":434,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/lif.jpg"},{"id":11,"name":"Finance","apps":200,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/fin.jpg"},{"id":12,"name":"News","apps":128,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/new.jpg"},{"id":13,"name":"Photography","apps":481,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/pho.jpg"},{"id":14,"name":"Entertainment","apps":1251,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/ent.jpg"},{"id":15,"name":"Business","apps":221,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/bus.jpg"},{"id":16,"name":"Sports","apps":199,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/spo.jpg"},{"id":17,"name":"Education","apps":433,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/edu.jpg"},{"id":18,"name":"Medical","apps":262,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/med.jpg"},{"id":19,"name":"Weather","apps":64,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/wea.jpg"},{"id":20,"name":"Reference","apps":419,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/ref.jpg"}]}
and i would like to convert to in an array like this
Array[0]
{
id => 1
name => Utilities
apps => 897
iconurl => http:\/\/static.apptrackr.org\/caticons\/uti.jpg
}
and so on
This looks like a JSON string. You can use json_decode() to convert it into a PHP variable, e.g.
$obj = json_decode($json);
print_r($obj->categories); // array of StdClass objects
You can access and iterate the categories array regularly
echo $obj->categories[0]->name; // Utilities
echo $obj->categories[1]->name; // Productivity
echo $obj->categories[2]->name; // Music
To convert the StdClass objects to arrays, you could do
$categories = array();
foreach (json_decode($json)->categories as $category) {
$categories[] = (array) $category;
}
print_r($categories);
You could also do it with a lambda function and array_map:
// Before PHP5.3
$categories = array_map(
create_function('$el', 'return (array) $el;'),
json_decode($json)->categories);
// After PHP5.3
$categories = array_map(
function($el) { return (array) $el; },
json_decode($json)->categories);
Erm, you can just set the 2nd parameter to convert JSON into an array instead of into an object:
$categories = json_decode($data, true);
take a look at get_object_vars
http://php.net/manual/en/function.get-object-vars.php
#Gordon seems correct - that looks like JSON. Assuming, though, that you're dealing with an "actual" PHP Object, then it will be iterable; simply run through it with a foreach and push each key/value pair into your destination array.

Does PHP feature short hand syntax for objects?

In javascript you can easily create objects and Arrays like so:
var aObject = { foo:'bla', bar:2 };
var anArray = ['foo', 'bar', 2];
Are similar things possible in PHP?
I know that you can easily create an array using the array function, that hardly is more work then the javascript syntax, but is there a similar syntax for creating objects? Or should I just use associative arrays?
$anArray = array('foo', 'bar', 2);
$anObjectLikeAssociativeArray = array('foo'=>'bla',
'bar'=>2);
So to summarize:
Does PHP have javascript like object creation or should I just use associative arrays?
For simple objects, you can use the associative array syntax and casting to get an object:
<?php
$obj = (object)array('foo' => 'bar');
echo $obj->foo; // yields "bar"
But looking at that you can easily see how useless it is (you would just leave it as an associative array if your structure was that simple).
There was a proposal to implement this array syntax. But it was declined.
Update    The shortened syntax for arrays has been rediscussed, accepted, and is now on the way be released with PHP 5.4.
But there still is no shorthand for objects. You will probably need to explicitly cast to object:
$obj = (object) ['foo'=>'bla', 'bar'=>2];
As of PHP 5.4, you can do this:
$array = ['foo'=>'bla', 'bar'=>2];
It's not much shorter, but you'll appreciate it if you need to use a lot of hard coded nested arrays (which isn't altogether uncommon).
If you want an object, you would still need to cast each array:
$object = (object) ['foo'=>'bla', 'bar'=>2];
According to the new PHP syntaxes,
You can use
$array = [1,2,3];
And for associative arrays
$array = ['name'=>'Sanket','age'=>22];
For objects you can typecast the array to object
$object = (object)['name'=>'Sanket','age'=>22];
There is no object shorthand in PHP, but you can use Javascript's exact syntax, provided you use the json_encode and json_decode functions.
The method provided by crescentfresh works very well but I had a problem appending more properties to the object. to get around this problem I implemented the spl ArrayObject.
class ObjectParameter extends ArrayObject {
public function __set($name, $value) {
$this->$name = $value;
}
public function __get($name) {
return $this[$name];
}
}
//creating a new Array object
$objParam = new ObjectParameter;
//adding properties
$objParam->strName = "foo";
//print name
printf($objParam->strName);
//add another property
$objParam->strUser = "bar";
There is a lot you can do with this approach to make it easy for you to create objects even from arrays, hope this helps .
Like the json_decode idea, wrote this:
function a($json) {
return json_decode($json, true); //turn true to false to use objets instead of associative arrays
}
//EXAMPLE
$cat = 'meow';
$array = a('{"value1":"Tester",
"value2":"'.$cat.'",
"value3":{"valueX":"Hi"}}');
print_r($array);

Categories