PHP Array stdClass Object - php

I have this array
Array (
[0] => stdClass Object (
[id] => 252062474)
[1] => stdClass Object (
[id] => 252062474)
[3] => stdClass Object (
[id] => 252062474)
)
I need echo all of id's
I tried,
foreach($result as $item) {
echo $item->id;
}
but no luck
I try json_decode()
again no luck I use php 5.5.8
I know this work
echo $item[0]->id;
but i don't how many index is there
any idea?

Maybe you are confused on foreach(). If this works:
echo $item[0]->id;
Then you would need:
foreach($item as $result) {
echo $result->id;
}

Try this-
Code
foreach($result as $p) {
echo $p['id'] . "<br/>";
}
Output
252062474
252062474
252062474

This array could be looped through and data could be retrieved. As you are saying its not working I have added the following code to illustrate how it works right from generating the array for you.
// generating an array like you gave in the example. Note that ur array has same value
// for all the ids in but my example its having different values
$arr = array();
$init = new stdClass;
$init->id = 252062474 ;
$arr[] = $init;
$init = new stdClass;
$init->id = 252062475 ;
$arr[] = $init;
$init = new stdClass;
$init->id = 252062476 ;
$arr[] = $init;
print_r($arr);
The above array is same as yours
Array ( [0] => stdClass Object ( [id] => 252062474 )
[1] => stdClass Object ( [id] => 252062475 )
[2] => stdClass Object ( [id] => 252062476 )
)
Now the following code will loop through and get the data as
foreach($arr as $key=>$val){
echo $key.' ID is :: '.$val->id;
echo '<br />';
}
The output will be
0 ID is :: 252062474
1 ID is :: 252062475
2 ID is :: 252062476

Try this
foreach($result as $item) {
$item = (array)$item;
echo $item['id'];
}

Related

PHP looping through array and appending to object

I have array of objects like so;
Array
(
[0] => stdClass Object
(
[Job] => stdClass Object
(
[ID] => 123
[Name] => Foo
)
)
[1] => stdClass Object
(
[Job] => stdClass Object
(
[ID] => 456
[Name] => BAR
)
)
)
I need to loop through the array and append some additional information to the object like 'Status', but I'm having some issues.
foreach($arrJobs as $key => $val) {
$arrJobs[$key]->Job->Status = new StdClass;
$arrJobs[$key]->Job->Status = $myStatus;
}
This appears to work, but I get the following warning;
Warning: Creating default object from empty value in...
Yes, create an object first. You cannot assign properties of null. That's why you need an instance of stdClass, php's generic empty class.
$arrJobs[$key] = new stdClass;
$arrJobs[$key]->foo = 1;
// And/or see below for 'nested' ...
$arrJobs[$key]->bar = new stdClass;
$arrJobs[$key]->bar->foo = 1;
According to my understanding to you question you just need to append properties to your existing objects. Don't create new objects in your loop
you just need this
foreach ($arrJobs as $obj)
{
$obj->job->status = $myStatus;
}
See the full code :
<?php
$obj1 = new \stdClass();
$obj1->job = new \stdClass();
$obj1->job->id = 123;
$obj1->job->name = "foo";
$obj2 = new \stdClass();
$obj2->job = new \stdClass();
$obj2->job->id = 456;
$obj2->job->name = "bar";
$array = [$obj1,$obj2];
var_dump($array);
foreach ($array as $obj)
{
$obj->job->status = "the status";
//add any properties as you like dynamicly here
}
echo "<br>\nafter<br>\n";
var_dump($array);
exit;
Now $obj1 and $obj2 has the new property 'status' ,see that demo : (https://eval.in/833410)
for ($i = 0; $i < count($arrJobs); $i++)
{
$arrJobs[$i]->Job->Status = new stdClass;
// other operations
}
Try this,
PHP
<?php
// Sample object creation.
$array = [];
$array = [0 => (object) ['Job'=>(object) ['ID'=>123, 'Name' => 'Foo']]];
foreach($array as $val) {
$val->Job->Status = (object) ['zero' => 0,'one' => 1]; // Status 0 and 1.
}
echo "<pre>";
print_r($array);
?>
Output
Array
(
[0] => stdClass Object
(
[Job] => stdClass Object
(
[ID] => 123
[Name] => Foo
[Status] => stdClass Object
(
[zero] => 0
[one] => 1
)
)
)
)

Append new key to an existing array in an object

I have an existing JSON array:
stdClass Object
(
[set] => Array
(
[0] => stdClass Object
(
[name] => agenda
)
[1] => stdClass Object
(
[name] => first aid
)
)
)
I need to add a new key to it, so the final JSON result is something like this:
set: [{
name: 'agenda',
value: 'Agenda'
}, {
code: 'first aid',
value: 'First Aid'
}],
This is what I've done so far:
$result = array();
foreach ($data->set as $k => $row) {
$result['name'][$k] = $row->name;
$result['value'][$k] = ucwords($row->name);
}
But I have ended up with:
Array
(
[name] => Array
(
[0] => agenda
[1] => aid kit
)
[value] => Array
(
[0] => Agenda
[0] => First Aid
)
)
How can I merge the above so the name and value keys are in pair rather then being separate?
Update $row directly to modify your existing $data:
foreach ($data->set as $row) {
$row->value = ucwords($row->name);
}
To do it the way you are attempting:
$result = $data;
foreach ($data->set as $k => $row) {
$result->set[$k]->value = ucwords($row->name);
}
Notice, $row is an object.
Your try this
$result = array();
$count = 0;
foreach ($data->set as $k => $row) {
$result[$count]['name'] = $row->name;
$result[$count]['value'] = ucwords($row->name);
$count++;
}
result this
Array
(
[0] => stdClass Object
(
[name] => agenda
[value] => Agenda
)
[1] => stdClass Object
(
[name] => first aid
[value] => First Aid
)
)
If you want to modify your existing object, you can just set the value property directly.
foreach ($data->set as $row) {
$row->value = ucwords($row->name);
}
If you want to create a result without modifying your original object or leaving references to its internal objects, you can clone each of the internal objects and add the new properties to the cloned objects.
$result = array();
foreach ($data->set as $k => $row) {
$obj = clone $row;
$obj->value = ucwords($row->name);
$result[$k] = $obj;
}

PHP last added in array replaces all stored array values

What I'm trying to do:
Get results from the database.
Get required values by assigning to an stdClass.
Put those objects in array. (<-The problem)
And output as JSON.
The objects are fine they get correct values. But when they are assigned to the array once, they replace all previous array values.
I'm using CodeIgniter to do the DB stuff.
The function:
function get_prizes(){
//All prize objects are stored here
$prizes = array();
//Prize object
$prize = new stdClass();
$prize->name1 = '';
//$prize->type = '';
//Getting the prizes from a simple database table
$query = $this->db->get('prizes');
if($query->num_rows() > 0){
foreach ($query->result() as $row):
$prize_name = $row->prize_name;
$prize->name1 = $prize_name;
//$prize->type = $prize_name;
$prizes[] = $prize;
echo " Item: " . print_r($prizes, true) . "<br>";
endforeach;
}
echo json_encode($prizes);
}
Output:
Item: Array ( [0] => stdClass Object ( [name1] => Radio ) )
Item: Array ( [0] => stdClass Object ( [name1] => Television ) [1] => stdClass Object ( [name1] => Television ) )
Item: Array ( [0] => stdClass Object ( [name1] => Toaster ) [1] => stdClass Object ( [name1] => Toaster ) [2] => stdClass Object ( [name1] => Toaster ) )
[{"name1":"Toaster"},{"name1":"Toaster"},{"name1":"Toaster"}]
I've tried array_push(). Also does the same thing.
You need to instantiate the object inside foreach loop:
function get_prizes()
{
// All prize objects are stored here
$prizes = array();
// Getting the prizes from a simple database table
$query = $this->db->get('prizes');
if ($query->num_rows() > 0) {
foreach($query->result() as $row):
// Prize object
$prize = new stdClass();
// $prize->type = '';
$prize->name1 = $row->prize_name;
$prizes[] = $prize;
endforeach;
}
echo json_encode($prizes);
}

PHP stdClass issue

I try to create an generic object which needs to be structuered like this:
[Content] => stdClass Object
(
[item] => Array
(
[0] => stdClass Object
(
[Value] => STRING
)
)
[item] => Array
(
[0] => stdClass Object
(
[Value] => ANOTHER STRING
)
)
)
This is my code:
$content = new stdClass();
$data = file('filname.csv');
foreach($data as $key => $val) {
$content->item->Value = $val;
}
This overwrites itself each time the loop iterates. By defining item as an array like this:
$content->item = array();
...
$content->item[]->Value = $val;
...the result is also not the estimated.
You are overwritting data each time even using array. You should create temporary object for storing value and then put them to item array.
$content = new \stdClass();
$content->item = array();
foreach($data as $key => $val) {
$itemVal = new \stdClass();
$itemVal->Value = $val;
$content->item[] = $itemVal;
}

Strip an XML object of its object status, and save the value contained inside

I have an object which contains an array, which contains an array, which contains an object:
stdClass Object
(
[path] => Array
(
[0] => Array
(
[0] => SimpleXMLElement Object
(
[0] => 44.6451471575972
)
)
)
)
What I need to turn that into is this:
stdClass Object
(
[path] => Array
(
[0] => Array
(
[0] => 44.6451471575972
)
)
)
Basically I need to get rid of that object, but save the value in that object. Using PHP, how do I do this?
EDIT: Here the code I am using to create the array:
$xml = simplexml_load_file('/Users/jasonburton/Sites/walkabout/csv-importer/xml/'.$old_route_id.'.xml');
$nodes = $xml->xpath('/markers/line/*');
$json = new stdClass;
$json->path = array();
foreach($nodes as $node){
foreach($node->attributes() as $index=>$value){
$values[] = $value;
if(count($values) == 2){
$json->path[] = array($values[0], $values[1]);
unset($values);
$values = array();
}
}
}
print_r($json);
$value is what contains the SimpleXMLObject that needs to be converted into the value.
Thanks!
Type cast $value with string: $values[] = (string)$value;

Categories