PHP Arrays and stdClass objects - php

I am working on a project to get the names of an array.
The arrays seem to be multidimensional, with the added bonus of being a stdclass Object. I am trying to select a key from the provided array but seem to have no luck selecting them.
echo($response->array[shoecompany]->array[1]->name);
from the information here
stdClass Object
(
[shoe] => shoemaker
[shoecompany] => Array
(
[0] => stdClass Object
(
[shoenumber] => 1
[name] => Blank
[1] => stdClass Object
(
[shoenumber] => 2
[name] => demo
)
[2] => stdClass Object
(
[shoenumber] => certificate
[name] => certofsale
)
)
)
Nothing i do seems to pull the information i need out of this. Any ways to go about pulling, said information.

The arrays seem to be multidimensional, with the added bonus of being a stdclass Object.
Arrays and objects aren't the same things.
I let you learn more about the specifics of both if you are curious.
Regarding access, yous use brackets - '[]' - when you want to access something in an array and an arrow - '->' - when you want to access an object's property :
$array['key'];
$object->property;
In your case, since only $response and the entries in the entry showcompany - I assume it's a typo - are objects, what you should write is :
$response->shoecompany[1]->name;
Which gives you in practical use :
foreach ($response->shoecompany as $val) {
echo $val->shoenumber, ' : ', $val->name, '<br>'; // Or whatever you want to print, that's for the sake of providing an example
}
If it is more convenient for you to handle exclusively arrays, you can also use get_object_vars() to convert an object properties to an array :
$response = get_object_vars($response);

Code should be like:
echo $response->shoecomapny[1]->name;
In short, to select key inside an object you need to use "->" operator and to select key inside array use "[]".

Related

How to "normalize" a php Object from SoapClient with inconsistent structure?

I have a php stdObject that is an object, and sometimes an array of Objects.
EDIT: It's been returned by SoapClient::__soapCall.
If it has one entry:
stdClass Object
(
[Event] => stdClass Object
(
[Nr] => 7050
[Date] => 2016-11-30T00:00:00
)
)
If it's got multiple entries:
stdClass Object
(
[Event] => Array
(
[0] => stdClass Object
(
[Nr] => 7015
[Date] => 2016-04-28T00:00:00
)
[1] => stdClass Object
(
[Nr] => 7016
[Date] => 2016-04-29T00:00:00
)
[2] => stdClass Object
(
[Nr] => 7017
[Date] => 2016-06-08T00:00:00
)
)
)
I don't see why, and I'd like to correct it.
Here's how I got there:
$items = $this->getAll(); // returns an Object with n entries
foreach($items as $item){
$fullItem = $this->item->getElementByID($item->Nr); // returns the full data for this entry
$item->Days = $fullItem->Days; // that's the one that can contain objects or just the data if it has one entry
}
My Questions:
Is that normal, that the same request returns different data types?
Should I "normalize" this and make an array of objects if there's only one entry?
Or is there an other recommended way to cope with it?
I don't think it's ok in this case. You should keep the interface the same. So if you are expecting an unknown number of elements it should always be a collection, even if in some cases only one element is returned. However if you expect only one element then the collection should be omitted.
$this->getAll(); //should always return a collection
$this->getOneById($id); //should return single item without collection, return null or throw exception if no element is found
On the question should you "normalize" (refactor) it I wold say it depends on the effort estimation and the benefit you'll gain form the refactoring. If this occurs in few places only and it's not likely to be used in any other place in the future I think you shouldn't bother. In case you decide to refactor be very careful and ensure the whole application is working properly. If you have tests - great.
I didn't declare it in the question, sorry: The data is the result of a soap client call:
$this->soapClient = new \SoapClient($wsdlUrl, array('trace' => DEBUG_SOAP));
// ...
$result = $this->soapClient->__soapCall($method, array($method => $params));
I think what confused me is the standard behaviour of SoapClient::__soapCall
SOAP functions may return one, or multiple values. If only one value
is returned by the SOAP function, the return value of __soapCall will
be a simple value (e.g. an integer, a string, etc). If multiple values
are returned, __soapCall will return an associative array of named
output parameters.
http://php.net/manual/en/soapclient.soapcall.php
Also, a very similar question: PHP SoapClient type mapping behaves differently
And here are two solutions from there:
"Normalize" (what's the correct word?) the data AFTER we got it:
if (is_object($variable)){
$variable = array($variable);
}
https://stackoverflow.com/a/6408780/160968
And, that would be the equivalent to refactoring the request BEFORE we get it – there's a setting for the soapClient!
$soapConfig = array(
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'trace' => true
);
$client = new SoapClient($wsdlUrl, $soapConfig);
https://stackoverflow.com/a/8008715/160968
Awesome!

Nested Array Foreach Issue

I am very basic new php learner, i having difficulty to get nested array value, here is my json result:
stdClass Object
(
[title] => Aao Raja - Gabbar Is Back | Chitrangada Singh
[link] => stdClass Object
(
[22] => Array
(
[0] => http://r8---sn-aigllnsk.c.docs.google.com/videoplayback?mime=video%2Fmp4&id=o-AExJcTxRDvCYsfgA1cIvQDs1v-pvLhKjTPdDh67X19vz&dur=145.542&itag=22&pl=48&ip=2a03:b0c0:1:d0::2f6:c001&sparams=dur,expire,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,nh,pl,ratebypass,source,upn&key=cms1&sver=3&expire=1437035009&upn=9lTw9Popb18&ratebypass=yes&source=youtube&lmt=1432539432699196&fexp=901816%2C9407809%2C9408142%2C9408420%2C9408710%2C9409172%2C9412774%2C9412846%2C9413149%2C9415664%2C9415958%2C9416126%2C9416370%2C9416656&ipbits=0&signature=3547894526817B37774A7838F8B68493CDD62101.3F143C74D76E8705800445A4CD4476C4F8BCD988&cms_redirect=yes&mm=31&mn=sn-aigllnsk&ms=au&mt=1437013301&mv=m&nh=IgpwcjAzLmxocjE0KgkxMjcuMC4wLjE&utmg=ytap1
[1] =>
[2] => hd720
)
[43] => Array
(
[0] => http://r8---sn-aigllnsk.c.docs.google.com/videoplayback?mime=video%2Fwebm&id=o-AExJcTxRDvCYsfgA1cIvQDs1v-pvLhKjTPdDh67X19vz&dur=0.000&itag=43&pl=48&ip=2a03:b0c0:1:d0::2f6:c001&sparams=dur,expire,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,nh,pl,ratebypass,source,upn&key=cms1&sver=3&expire=1437035009&upn=9lTw9Popb18&ratebypass=yes&source=youtube&lmt=1428933984759484&fexp=901816%2C9407809%2C9408142%2C9408420%2C9408710%2C9409172%2C9412774%2C9412846%2C9413149%2C9415664%2C9415958%2C9416126%2C9416370%2C9416656&ipbits=0&signature=266C126464ECDB4CC0FF076CD41F07BCC4DA7E34.08D9F13B7BF7D92FD1E1963336CC7FB8F19FE899&cms_redirect=yes&mm=31&mn=sn-aigllnsk&ms=au&mt=1437013301&mv=m&nh=IgpwcjAzLmxocjE0KgkxMjcuMC4wLjE&utmg=ytap1
[1] =>
[2] => medium
)
I can access the Title, but can't access the Link urls:
echo $title = $json->{'title'};
echo $link = $json->{'link'}->{'22'}->{'0'};
How can access the specific link array 22
This echo $title = $json->{'title'}; works because you are accessing an object's property and using -> is the correct way.
In this case $json->{'link'}->{'22'}->{'0'} you are trying to access an array item instead an object's property, because $json->{'link'}->{'22'} is an array and not an object. In this case, you should access it in this way: $json->{'link'}->{'22'}[0]. In order to avoid this kind of issues and, when you decode your JSON to a PHP object, you can pass true as a second parameter to the function json_decode and that will convert the whole object into an array. That way, you don't need to worry about accessing elements as object's attributes, you can access them, always, as array items. So, in this case, it would be: $json["link"]["22"][0].
You're confusing the way you access objects and arrays.
Getting the title is correct via $json->title, but the link should be $json->link->{'22'}[0] - a mixture of objects and arrays.
FYI the {'name'} notation is the same as name - only required when you are including variables in your object name e.g. {$someVar . 'name'}
I suppose you use json_decode() function. Do you know that you can get an array instead of StdClass Object? So, you can use.
<?php
$php_array = json_decode($json_string, true);

How to get data out of stdclass object?

I am using $this->db->get_where() to get data from database in codeigniter.
Its returning following which I got using print_r()
Its looks like array of stdClass object. Anyone who how to access values inside this array.
Array ( [0] =>
stdClass Object (
[id] => 1
[password321] => qwerty
[email123] => example#gmail.com
[username123] => xyz
)
)
It shows an array of objects. There is only one object in it.
If:
$var = $this->db->get_where();
Then:
echo $var[0]->id;
Access it like any other object.
echo $array[0]->id //1
echo $array[0]->username123 //xyz
And so on. If you have multiple objects inside the array, run it through a for loop to iterate the array.
For example:
for ($i=0;$i<sizeof($array);$i++) {
echo $array[$i]->[object property];
}

Navigating a multidimensional array with dynamic

I'm trying to figure out why it is that I cannot access the follow array with this statement:
var_dump($thevar[0]['product_id']);
Array
(
[d142d425a5487967a914b6579428d64b] => Array
(
[product_id] => 253
[variation_id] =>
[variation] =>
[quantity] => 1
[data] => WC_Product Object
(
[id] => 253
[product_custom_fields] => Array
(
[_edit_last] => Array
(
[0] => 1
)
[_edit_lock] => Array
(
[0] => 1345655854:1
)
[_thumbnail_id] => Array
(
[0] => 102
)
I can, however, access the 'product_id' using the dynamically created array name:
print_r($thevar['d142d425a5487967a914b6579428d64b']['product_id']);
The issue is, I don't know what that dynamic name is going to be on the fly...
There are several options for such scenarios.
Manually iterate over the array
You can use reset, next, key and/or each to iterate over the array (perhaps partially).
For example, to grab the first item regardless of key:
$item = reset($thevar);
Reindex the array
Sometimes it's just convenient to be able to index into the array numerically, and a small performance hit is not a problem. In that case you can reindex using array_values:
$values = array_values($thevar);
$item = $values[0]; // because $values is numerically indexed
Iterate with foreach
This would work for a single value as well as it works for more, but it might give the wrong impression to readers of the code.
foreach($thevar as $item) {
// do something with $item
}
If the array key is dynamic you might find the PHP function array_keys() useful.
It will return an array of the keys used in an array. You can then use this to access a particular element in the array.
See here for more:
http://php.net/manual/en/function.array-keys.php
Because PHP array are associative therefor you have to access them by key.
But you may use reset($thevar) to get first item.
Or array_values():
array_values($thevar)[0]
Or if you feel like overkill you may also use array_keys() and use the [0] element to address element like this:
$thevar[ array_keys($thevar)[0]]

array_count_values() with objects as values

I was wondering, is there something similar to array_count_values, but that works with objects ?
Let me explain:
array_count_values takes an array as argument, such as
[1]
Array (
[0] => banana
[1] => trololol
)
If i give that array to array_count_values, i will get something like:
[2]
Array (
[banana] => 1
[trololol] => 1
)
Now lets say that instead of strings, i have objects, that i want to count based on one of their properties. So i have:
[3]
Array (
[0] => stdClass Object (
[name] => banana
[description] => banana, me gusta!
)
[1] => stdClass Object (
[name] => trololol
[description] => trolololololol
)
)
And i'd want the magical-function-im-looking-for to count the number of objects with the same name property, returning the same input as [2]
Obviously i could easily do that on my own, but i was just wondering if there was a built-in function for that, since i couldnt seem to find one. Thanks, kind SOers!
No such function exists. You always need to first map the values you would like to count (and those values must be string or integer):
$map = function($v) {return $v->name;};
$count = array_count_values(array_map($map, $data));
Since PHP 7.0, you can use array_column for this.
$counts = array_count_values(array_column($array_of_objects, 'name'));
When this question was originally asked and answered array_column didn't exist yet. It was introduced in PHP 5.5, but it couldn't handle arrays of objects until 7.0.
Check out the Reflection classes to easily fetch information about your objects dynamically.

Categories