PHP looping through array and appending to object - php

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
)
)
)
)

Related

Using Associative arrays

I'm trying to access a position of a associative array which is inside of another array.
Here is my array:
Array
(
[order_data] => stdClass Object
(
[id_order] => 2
[id_client] => 1
[date_order] => 2022-04-03 18:43:18
[address] => meu puto
[city] => Rabinho
[email] => 40834#aeds.pt
[cellphone] => 919788427
[code_order] => QX669156
[status] => PENDIG
[message] =>
[created_at] => 2022-04-03 18:43:18
[updated_at] => 2022-04-03 18:43:18
)
[products_order] => Array
(
[0] => stdClass Object
(
[id_order_product] => 8
[id_order] => 2
[name_product] => Green Tshirt
[price_unity] => 35.15
[quantity] => 1
[created_at] => 2022-04-03 18:43:18
)
)
)
Im trying to access the field which name is name_product
and this is my code in order to do that:
$image = $order_details['products_order']['name_product']);
and this gives me the following error
Undefined array key "name_product"
probably it's just a simple thing.
You cannot access your data like your normally would an array, as said by #Omar_Tammam you are using Array objects.
Here is an example of how your data is set up and how you could use it:
# Creating your stdclass Object Array
$order_details['order_data'] = new stdClass();
$order_details['order_data']->id_order = 2;
$order_details['order_data']->id_client = 1;
$order_details['order_data']->date_order = "2022-04-03 18:43:18";
$order_details['order_data']->address = "meu puto";
$order_details['order_data']->city = "Rabinho";
$order_details['order_data']->email = "40834#aeds.pt";
$order_details['order_data']->cellphone = "919788427";
$order_details['order_data']->code_order = "QX669156";
$order_details['order_data']->status = "PENDING";
$order_details['order_data']->message = "";
$order_details['order_data']->created_at = "2022-04-03 18:43:18";
$order_details['order_data']->updated_at = "2022-04-03 18:43:18";
$order_details['products_order'][0] = new stdClass();
$order_details['products_order'][0]->id_order_product = "8";
$order_details['products_order'][0]->id_order = "2";
$order_details['products_order'][0]->name_product = "Green Tshirt";
$order_details['products_order'][0]->price_unity = "35.15";
$order_details['products_order'][0]->quantity = "1";
$order_details['products_order'][0]->created_at = "2022-04-03 18:43:18";
# To print all the data as example, showing stdClass Objects can
# be accessed through a foreach similar to an array
// foreach($order_details as $od){
// echo PHP_EOL, "_________________________", PHP_EOL;
// foreach($od as $a){
// if(!is_object($a)) echo $a, PHP_EOL;
// else foreach($a as $o) echo $o, PHP_EOL;
// }
// echo PHP_EOL, "_________________________", PHP_EOL;
// }
# this is wrong & will not work:
echo $order_details['products_order'][0]['name_product'];
# you would want to use this:
echo $order_details['products_order'][0]->name_product;
# more examples:
echo $order_details['order_data']->address;
echo $order_details['order_data']->city;
echo $order_details['order_data']->email;
echo $order_details['products_order'][0]->created_at;
# or as you wanted:
$image = $order_details['products_order'][0]->name_product;
echo $image;
# result would be: Green Tshirt
Online Sandbox Example: https://onlinephp.io/c/76370
I also created a recursive function that converts an array to or from an stdClass by reference:
function array_to_stdClass(&$array){
$tmp = $array;
$array = new stdClass();
foreach($tmp as $k => $v) $array->$k = (!is_object($v) && !is_array($v)) ? $v:array_to_stdClass($v);
return $array;
}
function stdClass_to_array(&$stdClass){
$tmp = $stdClass;
$stdClass = array();
foreach($tmp as $k => $v) $stdClass[$k] = (!is_object($v) && !is_array($v)) ? $v:stdClass_to_array($v);
return $stdClass;
}
Online Sandbox Example: https://onlinephp.io/c/4b183
the structure of the data is an array of array of object
this should works with you :
$image = $order_details['products_order'][0]->name_product;
$image = $order_details['products_order'][0]);
See the [0] in [0] => stdClass Object?
The following should work ...
$image = $order_details['products_order'][0]['name_product'];

When adding item to array, it overrides the first value

For some reason when I try to add an item to my array it overrides the fist item. I can't figure out why it is doing that. The first element should have an id of 1 and the second should be 2 but instead I get 2 and 2.
$array = new stdClass;
$arrays = [];
$ids = [1,2];
foreach ($ids as $id) {
$array->id = $id;
$arrays[] = $array;
print_r($arrays);
}
The result:
Array
(
[0] => stdClass Object
(
[id] => 1
)
)
Array
(
[0] => stdClass Object
(
[id] => 2
)
[1] => stdClass Object
(
[id] => 2
)
)
You are updating the same object, you need to put 2 different objects within the array, bring the class declaration within the loop.
foreach ($ids as $id) {
$array = new stdClass; // object initialization
$array->id = $id;
$arrays[] = $array;
print_r($arrays);
}

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;
}

PHP Array stdClass Object

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'];
}

Help understanding a php function - the meaning of $array[]; the [] part

private function jsonArray($object)
{
$json = array();
if(isset($object) && !empty($object))
{
foreach($object as $obj)
{
$json[]["name"] = $obj;
}
}
return $json;
}
We are grabbing an object, and if the conditional is met, we iterate over that object.
Then... I'm lost on this reading... :s
What's the meaning of the [] here?
$json[]["name"] = $obj;
Thanks in advance,
MEM
$json[] adds an element at the end of the array (numeric index). It's the same as having the following code:
$array=array();
$i=0;
foreach($something as $somethingElse)
{
$array[]=$somethingElse;
//is equivalent, in some way, to
$array[$i++]=$somethingElse;
}
That's the equivalent to this:
$json[] = array('name' => $obj);
It adds the contents of $obj to a new field in $json and there in the field "name".
Little example:
$arr = array();
$arr[] = "Hello";
$arr[] = "World!";
Then, $arr will contain:
Array (
0 => "Hello",
1 => "World!"
)
Or, as in your example with another array in the field:
$arr = array();
$arr[]["text"] = "Hello";
$arr[]["text"] = "World!";
Becomes
Array (
0 => Array (
"text" => "Hello"
),
1 => Array (
"text" => "World!"
)
)
$json[] automatically creates a new element at the end of the array - here is an example:
$json[]["name"] = "object1";
$json[]["name"] = "object2";
$json[]["name"] = "object3";
$json[]["name"] = "object4";
And here is what it displays:
Array
(
[0] => Array
(
[name] => object1
)
[1] => Array
(
[name] => object2
)
[2] => Array
(
[name] => object3
)
[3] => Array
(
[name] => object4
)
)

Categories