stdClass to array? - php

i have:
stdClass Object
(
[0] => stdClass Object
(
[one] => aaa
[two] => sss
)
[1] => stdClass Object
(
[one] => ddd
[two] => fff
)
[2] => stdClass Object
(
[one] => ggg
[two] => hhh
)
}
and i must get this with keys, for example:
$var = $stdClass[0];
but i have error:
Fatal error: Cannot use object of type stdClass as array in
Is possible parse this stdClass to array and use this with keys?

Cast it to an array:
$array = (array)$stdClass;

If you're using json_decode to convert that JSON string into an object, you can use the second parameter json_decode($string, true) and that will convert the object to an associative array.
If not, what everybody else has said and just type cast it
$array = (array) $stdClass;

Your problem is probably solved since asking, but for reference, quick uncle-google answer:
function objectToArray($d) {
if(is_object($d)) {
$d = get_object_vars($d);
}
if(is_array($d)) {
return array_map(__FUNCTION__, $d); // recursive
} else {
return $d;
}
}
Full article here. Note I'm not associated with the original author in any way.

Cast it
$array = (array) $stdObject;

Of course you can typecast, $var = (array) $obj;, but I would suggest ArrayAccess to your class.
By using ArrayAccess, you can then treat your objects and data as if it was an array, or natively as an object.

Cast it into an array. Currently it is not readable to PHP as an array.
$array = (array)$stdClass;

Essentially, just type cast it:
$arr = (array)$obj;
$var = $arr[0];
But read the caveats here.

If you have an nested array you can used json_encode and json_decode to convert the whole object to an array:
$result = json_decode(json_encode($source), JSON_OBJECT_AS_ARRAY);

This one worked for me,
The decoding and encoding makes for a regular array
$array = json_decode(json_encode($object), True);

function load_something () : \stdClass {
$result = new \stdClass();
$result->varA = 'this is the value of varA';
$result->varB = 'this is the value of varB';
$result->varC = 'this is the value of varC';
return $result;
}
$result = load_something();
echo ($result instanceof stdClass)?'Object is stdClass':'Object is not stdClass';
echo PHP_EOL;
print_r($result);
//directly extract a variable from stdClass
echo PHP_EOL . 'varA = ' . ($result->varA);
//convert to array, then extract
$array = (array)$result;
echo PHP_EOL . 'varA = ' . $array['varA'];

stdClass is an object so u can access value from it like
echo stdClass->one;

Related

get array value from std object in php

I have an array like below. I want to extract the values . Help me out please. But this doesn't print anything. Please help me.Any help would be appreciated.May you all find this question similar.But I am unable to find any answer,because that's the way we do to find the array values.
Array
(
[0] => stdClass Object
(
[bHeader] => stdClass Object
(
[ei] => NSE
[seg] => I
)
[cNetChangeIndicator] =>
[fClosingIndex] => 10558.5
[fHighIndexValue] => 10532
[fIndexValue] => 10469
[fLowIndexValue] => 10438.5
[fOpeningIndex] => 10499.5
[fPercentChange] => -0.85
[sIndexName] => 962450
[fChange] => -89.5
[iIdxId] => 311
)
)
Thanks in advance
convert your object in to array using
$array = (array) $yourObject;
if you use json_decode than give second parameter true e.g
$array = json_decode($jsonStr,TRUE);
It will return array so no need to typecast(conveting) obj to array
also used operator '->' which help to fetch data from object
You are accessing the object in the array as if it is also an array.
You need to access the object's properties using ->
echo $arr[0]->fIndexValue;
echo $arr[0]->fChange;
echo $arr[0]->fPercentChange';
For example:
$obj = new stdClass;
$obj->fIndexValue = 10469;
$arr = array();
$arr[0] = $obj;
echo $arr[0]->fIndexValue;
Prints "10469".
Try this to print the whole thing, assuming your var is $arr:
print_r($arr);
Or for variables
print($arr[0]-->fIndexValue);

php echo from array_chunk as string

I want to echo an array_chunk as string, how do I do that ?
here is the code
$rt = $this->db->query("SELECT id_reg_pd FROM 043104_kuliahmhs_20152_2a0dc380_temp");
$_datao = array_chunk($rt->result(), 3);
foreach($_datao as $batman => $robin) {
print_r($robin);
}
I want echo id_reg_pd as string.
I have tried tried :
echo $robin->id_reg_pd;
but get php error like this
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Here the array from print_r($robin);
Array
(
[0] => stdClass Object
(
[id_reg_pd] => 001be76b-4e58-4cea-96cf-fee2d8e0abdc
)
[1] => stdClass Object
(
[id_reg_pd] => 001d4fe5-73f5-4bae-b126-1f787ea0104e
)
[2] => stdClass Object
(
[id_reg_pd] => 002ab28b-e0b9-464a-89fb-12552512a5d0
)
)
Loop over $robin and then check
foreach($robin as $value)
{
echo $value->id_reg_pd;
}
try like this
for($i=0;$i<count($_datao);$i++){
$newarr = (array) $robin[$i];
echo $newarr['id_reg_pd'];
}
Sahil is incorrect. It is not true that you must use a for / foreach loop to achieve your desired result. array_column() works on an array of objects. If you can use a simple implode() call to convert your array to a string, then here is a simple one-liner:
Code (Demo):
$robin=[
(object)['id_reg_pd'=>'001be76b-4e58-4cea-96cf-fee2d8e0abdc'],
(object)['id_reg_pd'=>'001d4fe5-73f5-4bae-b126-1f787ea0104e'],
(object)['id_reg_pd'=>'002ab28b-e0b9-464a-89fb-12552512a5d0']
];
//print_r($robin); // uncomment to see for yourself
//var_export(array_column($robin,'id_reg_pd')); // uncomment to see for yourself
echo implode(', ',array_column($robin,'id_reg_pd')); // implode with whatever glue you wish
Output:
001be76b-4e58-4cea-96cf-fee2d8e0abdc, 001d4fe5-73f5-4bae-b126-1f787ea0104e, 002ab28b-e0b9-464a-89fb-12552512a5d0

How to convert Std class object data to array in php

$postdata= "stdClass Object
(
[created] => 1326853478
[livemode] =>
[id] => evt_00000000000000
[type] => invoice.payment_succeeded
...........................
))";
$event = json_decode($postdata);
echo "<pre>";
print_r($event);
Can't std class object to array in php?I am using json_decode but its not working just get empty array.I am giving my result data std class object assign in variable its anything wrong that's why its showing not working?
you can use :
$array = json_decode(json_encode($data), true);
print_r($array);
The easiest way is to cast it:
$array = (array) $stdClass;
try this
$event = json_decode($data, true);
print_r($event);

Array mapping in PHP with keys [duplicate]

This question already has answers here:
Generate an associative array from an array of rows using one column as keys and another column as values
(3 answers)
Closed 6 months ago.
Just for curiosity (I know it can be a single line foreach statement), is there some PHP array function (or a combination of many) that given an array like:
Array (
[0] => stdClass Object (
[id] => 12
[name] => Lorem
[email] => lorem#example.org
)
[1] => stdClass Object (
[id] => 34
[name] => Ipsum
[email] => ipsum#example.org
)
)
And, given 'id' and 'name', produces something like:
Array (
[12] => Lorem
[34] => Ipsum
)
I use this pattern a lot, and I noticed that array_map is quite useless in this scenario cause you can't specify keys for returned array.
Just use array_reduce:
$obj1 = new stdClass;
$obj1 -> id = 12;
$obj1 -> name = 'Lorem';
$obj1 -> email = 'lorem#example.org';
$obj2 = new stdClass;
$obj2 -> id = 34;
$obj2 -> name = 'Ipsum';
$obj2 -> email = 'ipsum#example.org';
$reduced = array_reduce(
// input array
array($obj1, $obj2),
// fold function
function(&$result, $item){
// at each step, push name into $item->id position
$result[$item->id] = $item->name;
return $result;
},
// initial fold container [optional]
array()
);
It's a one-liner out of comments ^^
I found I can do:
array_combine(array_map(function($o) { return $o->id; }, $objs), array_map(function($o) { return $o->name; }, $objs));
But it's ugly and requires two whole cycles on the same array.
The easiest way is to use an array_column()
$result_arr = array_column($arr, 'name', 'id');
print_r($result_arr );
Out Put
Array (
[12] => Lorem
[34] => Ipsum
)
The easiest way is to use a LINQ port like YaLinqo library*. It allows performing SQL-like queries on arrays and objects. Its toDictionary function accepts two callbacks: one returning key of the result array, and one returning value. For example:
$userNamesByIds = from($users)->toDictionary(
function ($u) { return $u->id; },
function ($u) { return $u->name; }
);
Or you can use a shorter syntax using strings, which is equivalent to the above version:
$userNamesByIds = from($users)->toDictionary('$v->id', '$v->name');
If the second argument is omitted, objects themselves will be used as values in the result array.
* developed by me
Because your array is array of object then you can call (its like a variable of class) try to call with this:
foreach ($arrays as $object) {
Echo $object->id;
Echo "<br>";
Echo $object->name;
Echo "<br>";
Echo $object->email;
Echo "<br>";
}
Then you can do
// your array of object example $arrays;
$result = array();
foreach ($arrays as $array) {
$result[$array->id] = $array->name;
}
echo "<pre>";
print_r($result);
echo "</pre>";
Sorry I'm answering on handphone. Can't edit the code

Converting array and objects in array to pure array [duplicate]

This question already has answers here:
Convert a PHP object to an associative array
(33 answers)
Closed 1 year ago.
My array is like:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => demo1
)
[1] => stdClass Object
(
[id] => 2
[name] => demo2
)
[2] => stdClass Object
(
[id] => 6
[name] => otherdemo
)
)
How can I convert the whole array (including objects) to a pure multi-dimensional array?
Have you tried typecasting?
$array = (array) $object;
There is another trick actually
$json = json_encode($object);
$array = json_decode($json, true);
You can have more info here json_decode in the PHP manual, the second parameter is called assoc:
assoc
When TRUE, returned objects will be converted into associative arrays.
Which is exactly what you're looking for.
You may want to try this, too : Convert Object To Array With PHP (phpro.org)
Just use this :
json_decode(json_encode($yourArray), true);
You can use array_walk to convert every item from object to array:
function convert(&$item , $key)
{
$item = (array) $item ;
}
array_walk($array, 'convert');
Assuming you want to get to this pure array format:
Array
(
[1] => "demo1",
[2] => "demo2",
[6] => "otherdemo",
)
Then I would do:
$result = array();
foreach ($array as $object)
{
$result[$object->id] = $object->name
}
(edit) Actually that's what I was looking for possibly not what the OP was looking for. May be useful to other searchers.
You should cast all objets, something like :
$result = array();
foreach ($array as $object)
{
$result[] = (array) $object
}
As you are using OOP, the simplest method would be to pull the code to convert itself into an array to the class itself, you then simply call this method and have the returned array populate your original array.
class MyObject {
private $myVar;
private $myInt;
public function getVarsAsArray() {
// Return the objects variables in any structure you need
return array($this->myVar,$this->myInt);
}
public function getAnonVars() {
// If you don't know the variables
return get_object_vars($this);
}
}
See: http://www.php.net/manual/en/function.get-object-vars.php for info on get_object_vars()
it you have object and you want to set a value as array
use
$this->object->pluck('name');
then you get the value as array of names like
["name1", "name2", "name3"];

Categories