i am having difficulty with php foreach loop through array - php

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

Related

Echoing array values

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

PHP how to properly loop through json with multiple levels as object

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

wordpress $wpdb select results to an array

$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.
}
}

Converting array and objects in array to pure array [duplicate]

This question already has answers here:
Convert a PHP object to an associative array
(33 answers)
Closed 1 year ago.
My array is like:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => demo1
)
[1] => stdClass Object
(
[id] => 2
[name] => demo2
)
[2] => stdClass Object
(
[id] => 6
[name] => otherdemo
)
)
How can I convert the whole array (including objects) to a pure multi-dimensional array?
Have you tried typecasting?
$array = (array) $object;
There is another trick actually
$json = json_encode($object);
$array = json_decode($json, true);
You can have more info here json_decode in the PHP manual, the second parameter is called assoc:
assoc
When TRUE, returned objects will be converted into associative arrays.
Which is exactly what you're looking for.
You may want to try this, too : Convert Object To Array With PHP (phpro.org)
Just use this :
json_decode(json_encode($yourArray), true);
You can use array_walk to convert every item from object to array:
function convert(&$item , $key)
{
$item = (array) $item ;
}
array_walk($array, 'convert');
Assuming you want to get to this pure array format:
Array
(
[1] => "demo1",
[2] => "demo2",
[6] => "otherdemo",
)
Then I would do:
$result = array();
foreach ($array as $object)
{
$result[$object->id] = $object->name
}
(edit) Actually that's what I was looking for possibly not what the OP was looking for. May be useful to other searchers.
You should cast all objets, something like :
$result = array();
foreach ($array as $object)
{
$result[] = (array) $object
}
As you are using OOP, the simplest method would be to pull the code to convert itself into an array to the class itself, you then simply call this method and have the returned array populate your original array.
class MyObject {
private $myVar;
private $myInt;
public function getVarsAsArray() {
// Return the objects variables in any structure you need
return array($this->myVar,$this->myInt);
}
public function getAnonVars() {
// If you don't know the variables
return get_object_vars($this);
}
}
See: http://www.php.net/manual/en/function.get-object-vars.php for info on get_object_vars()
it you have object and you want to set a value as array
use
$this->object->pluck('name');
then you get the value as array of names like
["name1", "name2", "name3"];

Extract data from an XML object

How do I extract the data from that XML object, which is a value of a certain array:
Array (
[Title] => SimpleXMLElement Object (
[0] => The Key of Life; A Metaphysical Investigation
)
[ASIN] => SimpleXMLElement Object ( [0] => 0982385099 ) ...
)
I did a foreach of the array like:
foreach ($ArrayName as $FieldLabel => $FieldValue) {
$Variable = $FieldValue[0]....
}
...but still, it gets the whole XML object as the field value. I wanted it to extract the value only not the whole object.
All simple xml objects are iteratable. Basically think of any object as a set, and some set's just happen to contain one object.
To extract your value do this
foreach($title as $item)
{
$list_of_titles = (string) $item;
}
print_r($list_of_titles);
So basically I typecast every item into a string from an object.

Categories