This is a common question, but I've not been able use solutions to what I'm working on. I'm having trouble understanding how echoing the values in an array works, any help is appreciated. The following code;
$sql = 'someQuery';
$dev='someString';
$device = $client->executeSQLQuery(array("sql"=>$sql));
echo "<pre>";
print_r($device);
echo "</pre>";
Will yield the following output;
stdClass Object
(
[return] => stdClass Object
(
[row] => Array
(
[0] => stdClass Object
(
[name] => someString
[userid] => user1
)
[1] => stdClass Object
(
[name] => someString
[userid] => user2
)
)
)
)
This is very easy to understand. I also understand that in order to echo the contents of this output I need to use a foreach loop. I'm trying to echo each instance of userid (which occurs twice in the output).
foreach($device as $first)
{
if( is_array($first->row) )
{
$userid = $first->userid;
foreach($userid as $second)
{
echo "<b>UserID</b><br> " . $device->return->row->userid . $
}
}
}
So, this does not work and likely because I didn't learn it the proper way the first time. In this case, as I understand it, the if statement doesn't even need to be there because we don't need to evaluate if the content is an array (it's not). Can someone explain the logic of how to go through the array and echo each instance of the object userid?
Pay attention on the print_r output. $device is stdClass not a array, it has a property called return which also is a stdClass. Once again has a property called row this property is a array.
So as #derek-pollard said, you need to do, something like this:
foreach($device->return->row as $info) {
echo "<b>UserID</b><br> " . $info->userid;
echo "<b>UserName</b><br> " . $info->name;
}
It'll work because $device->return->row will return the array of users. For beginners, the foreach will iterate once for each item (inside the array) and $info will have the content of the current item.
Finally it will print:
<b>UserID</b><br> user1
<b>UserName</b><br> someString
<b>UserID</b><br> user2
<b>UserName</b><br> someString
In your example row is an array of objects. userid is just an object's property which is assigned with primitive value. You can't iterate through such kind of properties:
foreach($device->return->row as $obj)
{
echo $obj->userid; // this gives 'userid' value
}
Your assumption will be reasonable if you would store some array in userid property
Related
i need help fetching values from an array,
Array ( [0] => stdClass Object (
[service] => text
[reference] => 12345678
[status] => approved
[sender] => webmaster
[mobile] => 123456789
[message] => I need hekp.
[data] =>
[price] => 3.2500
[units] => 1
[length] => 86c/1p
[send_date] => 2021-05-20 15:42:41
[date] => 2021-05-20 15:42:41 ) )
what i have done
$response = json_decode($result);
foreach($response as $value){
echo $value['units'];
}
i get an error 500 please kindly guide me i am lost
stdClass Object is telling us you have an object inside your array. so your $response structure looks like this in code:
[
{
"service": "text",
"reference": 12345678
}
]
try this:
$response = json_decode($result);
foreach($response as $value){
echo $value->units;
}
in response yo your comment on this answer:
if you wanted to neaten this up you could replace the second reference to $response->data with $values:
$values = $response->data;
foreach($values as $value){
echo "<table>
<td>$value->reference</td>
<td>$value->message</td>
<td>$value->sender</td>
<td>$value->mobile</td>
<td>$value->status</td>
<td>$value->units</td>
</table>";
}
I suspect this is what you were going for when you wrote it out, but essentially you were declaring $values and then not using it.... then making a call to the same collection as $values.
Next time enable error_reporting and include any errors and warnings you get.
In this instance the issue is fairly obvious. Your array only contains a single item - and that item is an object. The echo construct expects a string (but can handle an implicit cast from other scalar types). It doesn't know how to output the object. If the object implements the __tostring() method then PHP will call that to get a string to output. But stdClass (the type of object you have here) does not have a _tostring() method.
You also don't state in your question if you are looking for a specific value in the data - i.e. if you know its name - which is rather critical for how you approach the solution.
That you have a stdclass object suggests that you have loaded it from serialized representation of data such as JSON. If you had converted this input to an array instead of an object (most of the things in PHP which will return stdclass objects can also return associative arrays) you could simply have done this:
function walk_array($in, $depth)
{
if ($depth><MAXDEPTH) {
// because you should never use unbounded recursion
print "Too deep!\n";
return;
}
foreach ($in as $k=>$item) {
print str_pad("", $depth, "-") . $k . ":";
if (is_array($item)) {
print "\n";
walk_array($item, $depth+1);
} else {
print $item;
}
}
}
You can convert an object into an associative array with get_object_vars()
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 "[]".
Here is the Json data stored in variable $json
[Data] => Array
(
[id_number] => Array
(
[value] => 123445567
[link] => 1234556
[class] =>
)
[date] => Array
(
[value] => 04-18-14
[link] => 1234556
[class] =>
)
Currently I access the lower levels like this:
foreach($json['Data'] as $data) {
foreach ($data['id_number'] as $id) {
print $id['value'];
}
}
There is only one result for id_number and only one result for date. Do I really need this second foreach loop? Isn't there a way to access it by just going to the lower level as an object so it would be something like
print $data->id_number->value
Thank you.
Since you have decoded the JSON string as an array you could do
foreach($json['Data'] as $data) {
print $data['id_number']['value'];
}
If you had decoded it into an object (don't set the second parameter to be true) then you could simply do it like you mentioned
foreach($json->Data as $data)
print $data->id_number->value;
Manual
You can retrieve the elements individually (without looping) by:
$id_number = $json['Data']['id_number']['value'];
$date = $json['Data']['date']['value'];
//etc ...
You can use:
$json['Data'][idnr]->value
If you know the id that is ofc, else you will have to loop
$wp->get_results will return an array and formats the array depends if the second parameter is specified; if not, it is default to an object, right? But my question is it possible to retrieve results then store it the an array? Like this $arr = array(1,2,3,4,5)? What my main concern is this.. I want to search in the array if the value is present.
Now I can't do a in_array if the returned results is like this.
$arr = array(array('1'), array('2'), array('3'), array('4'), array('5'));
Any help would be much appreciated. Thanks.
EDITED
my $arr would look like this
Array ( [0] => stdClass Object ( [code] => 8 [id] => ) [1] => stdClass Object ( [code] => 1 [id] => ) )
EDITED
Found a solution:
if (in_array(array('1'), $arr) {
// found value
}
You can not match directly, for matching, it you will have to do something like this :
$arr = array(array('1'), array('2'), array('3'), array('4'), array('5'));
foreach($arr as $newar)
{
if (in_array('2',$newar))
{
echo 'hello';
}
}
I'm not really following the problem here, but assuming you want to find a specific value inside the wpdb results......
foreach($arr as $key => $row) {
if($row->code == $VALUE_YOU_WANT_TO_MATCH) {
// do something
break;
}
}
Note: $arr is an array of objects, its not a multidimensional array.
say for example I want to check if if code = 1 exist in my result.
foreach($arr as $myarr){
if ($myarr->code == "1"){
echo "record was found\n";
break;//this line makes the foreach loop end after first success.
}
}
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];
}