Using Associative arrays - php

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

Related

remove duplicate items from object php

{"id":34,"first_name":"xus"}
{"id":34,"first_name":"xus"}
{"id":4,"first_name":"ABC"}
{"id":4,"first_name":"ABC"}
$newlist = [];
$values = [];
foreach ($appointment_list as $key => $value) {
# code...
$values[] = $value['users'];
foreach($values as $val){
$newlist[$val->id]=$values;
}
unset($newlist[$key][$values]);
}
I want to remove duplicate value from object show distinct value base on id and want to count duplicate exist of each id
Expected
id 34 has 2 duplicate
and it should return one object
{"id":34,"first_name":"xus", "count":2}
something like that
You can use array_reduce
$arr = array(
array("id" => 34,"first_name" => "xus"),
array("id" => 34,"first_name" => "xus"),
array("id" => 4,"first_name" => "ABC"),
array("id" => 4,"first_name" => "ABC"),
);
$result = array_reduce($arr, function($c, $v){
if ( !isset( $c[$v["id"]] ) ) {
$c[$v["id"]] = $v;
$c[$v["id"]]["count"] = 1;
} else {
$c[$v["id"]]["count"]++;
}
return $c;
}, array());
$result = array_values( $result );
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[0] => Array
(
[id] => 34
[first_name] => xus
[count] => 2
)
[1] => Array
(
[id] => 4
[first_name] => ABC
[count] => 2
)
)
The simplest way of doing this is to create an empty array and map your objects using "id" as a key.
Here's the working snippet
<?php
$objectsRaw = [];
$objectsRaw[] = '{"id":34,"first_name":"xus"}';
$objectsRaw[] = '{"id":34,"first_name":"xus"}';
$objectsRaw[] = '{"id":4,"first_name":"ABC"}';
$objectsRaw[] = '{"id":4,"first_name":"ABC"}';
# decode the json objects into PHP arrays
$objects = array_map(
function($objectJson) {
$object = json_decode($objectJson, true);
return $object;
},
$objectsRaw
);
# map the objects
$result = [];
foreach($objects as $object) {
if (array_key_exists($object['id'], $result) === false) {
$object['count'] = 1;
$result[$object['id']] = $object;
continue;
}
$result[$object['id']]['count']++;
}
# encode result
$resultRaw = array_map('json_encode', $result);
# would look like
# Array
# (
# [34] => {"id":34,"first_name":"xus","count":2}
# [4] => {"id":4,"first_name":"ABC","count":2}
# )
# reset array keys (if you need this)
$resultRaw = array_values($resultRaw);
# would look like
# Array
# (
# [0] => {"id":34,"first_name":"xus","count":2}
# [1] => {"id":4,"first_name":"ABC","count":2}
# )

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

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

Manipulate Array structure using php

I have an array structure like this
Array
(
[0] => stdClass Object
(
[foo] => 9992
[bar] => 1508
)
[1] => stdClass Object
(
[foo] => 10115
[bar] => 1598
)
[2] => stdClass Object
(
[foo] => 10263
[bar] => 1690
)
[3] => stdClass Object
(
[foo] => 10363
[bar] => 1794
)
[4] => stdClass Object
(
[foo] => 10486
[bar] => 1904
)
)
Now I would like to convert this structure to this:
Array
(
[0] => stdClass Object
(
[name] => 'foo'
[data] => Array (
9992, 10115, 10263, 10363, 10486
)
)
[1] => stdClass Object
(
[name] => 'bar'
[data] => Array(
1508, 1598, 1690, 1794, 1904
)
)
)
I have tried this code but it does not gave me the expected structure
$return = array();
$i = 0;
foreach($object as &$row) {
foreach( $row as $key => $val ) {
$return[$i]['name'] = $key;
// This is my custom function that does the same
// thing for objects as array_search does for arrays
$search = object_search($key, $row);
if( $search ) {
$return[$search]['data'][] = $val;
} else {
$return[$i]['data'][] = $val;
}
}
$i++;
}
return $return;
Try this
$result = array();
foreach ($array1 as $row) {
foreach ($row as $key => $value) {
$result[$key][] = $value;
}
}
$result2 = array();
foreach ($result as $key => $value) {
$obj = array();
$obj['name'] = $key;
$obj['data'] = $value;
$result2[] = $obj;
}
The code may fail, but you got the idea.
If you could give me your array in php code I can test my code again.
$c1 = new stdClass();
$c1->foo = 123;
$c1->bar = 345;
$c2 = new stdClass();
$c2->foo = 444;
$c2->bar = 555;
$arr = array();
$arr[] = $c1;
$arr[] = $c2;
$tfoo = array();
$tbar = array();
foreach($arr as $a) {
$tfoo[] = $a->foo;
$tbar[] = $a->bar;
}
$foo = array_unique($tfoo);
$bar = array_unique($tbar);
$result = array();
$result[0] = new stdClass();
$result[0]->name = "foo";
$result[0]->data = $foo;
$result[1] = new stdClass();
$result[1]->name = "bar";
$result[1]->data = $bar;
print_r($result);

PHP - how to push the result of SimpleXML parsing correctly into the Array?

I'm trying to push the result of xml parsing to the multidimensional array. The structure of XML is here. The PHP procedure is (not working correctly):
$xml_url = simplexml_load_file("url to the xml document");
$data = $xml_url->xpath('MULTIPLE/SINGLE/KEY');
$current = 0;
$topics_list = array();
//display list of 'chapters'
foreach($data as $chap_name) {
if ($chap_name['name'] == 'name') {
echo $chap_name->VALUE . '<br />';
$topics_list[$current]['chapter'] = $chap_name->VALUE;
}
}
$data2 = $xml_url->xpath('MULTIPLE/SINGLE/KEY[#name="modules"]/MULTIPLE/SINGLE/KEY');
//display list of 'topics' & 'contents'
foreach($data2 as $topic_name) {
if ($topic_name['name'] == 'name') {
echo $topic_name->VALUE . '<br />';
$topics_list[$current]['topic'] = $topic_name->VALUE;
}
if ($topic_name['name'] == 'description') {
echo $topic_name->VALUE . '<br />';
$topics_list[$current]['content'] = $topic_name->VALUE;
}
}
print_r($topics_list);
The structure of Array in which I want to push the data is:
Array (
[0] => Array (
[chapter] => Chapter_name1
[name] => Topic_name1
[content] => Content_of_the_topic1
)
[1] => Array (
[chapter] => Chapter_name1
[name] => Topic_name2
[content] => Content_of_the_topic2
)
[2] => Array (
[chapter] => Chapter_name2
[name] => Topic_name2
[content] => Content_of_the_topic2
)
.....
)
UPDATE: This is the result of above mentioned code proccessing:
Array(
[0] => Array(
[chapter] => SimpleXMLElement Object
(
[0] => STÖRUNGEN
)
[topic] => SimpleXMLElement Object
(
[0] => 3.25 Starke Blutung
)
[content] => SimpleXMLElement Object
(
[#attributes] => Array
(
[null] => null
)
)
)
)
Try 'casting' the value from the SimpleXMLElement to a string when adding it to the array, like this:
// add (string) after the '='
$topics_list[$current]['content'] = (string) $topic_name->VALUE;
This will make sure the value of the SimpleXMLElement element is added as a string, not as a n object.
Also (as marked by others), make sure you increment $current to prevent each record overwriting the previous one
Here's your code updated; But read the comments in the code
$xml_url = simplexml_load_file("url to the xml document");
$data = $xml_url->xpath('MULTIPLE/SINGLE/KEY');
$data2 = $xml_url->xpath('MULTIPLE/SINGLE/KEY[#name="modules"]/MULTIPLE/SINGLE/KEY');
$current = 0;
$topics_list = array();
//display list of 'chapters'
foreach($data as $chap_name) {
if ($chap_name['name'] == 'name') {
$topics_list[$current]['chapter'] = (string) $chap_name->VALUE;
}
// display list of 'topics' & 'contents'
// NOTE: Not sure if this will work as expected, based on
// the name 'topic', I suspect a single chapter
// will have *multiple* topics.
// Also, those 'topics' will probably need to be 'matched'
// to the current 'chapter', so that only the topics for
// *this* chapter will be added here!
foreach($data2 as $topic_name) {
if ($topic_name['name'] == 'name') {
$topics_list[$current]['topic'] = (string) $topic_name->VALUE;
}
if ($topic_name['name'] == 'description') {
$topics_list[$current]['content'] = (string) $topic_name->VALUE;
}
}
$current++;
}
print_r($topics_list);

Categories