php foreach/for acting weirdly - php

Someone can solve this mystery? i have two code samples. I think that the second example does same thing as first example but apparently it doesnt.
this works:
print_r($this->facebook->my_retrieve_timeline()['data'][0]->message);
print_r($this->facebook->my_retrieve_timeline()['data'][2]->message);
this doesnt:
for ($i=0; $i <11; $i++) {
echo $this->facebook->my_retrieve_timeline()['data'][$i]->message;
}
error:
Message: Undefined property: stdClass::$message
array looks like this:
Array
(
[data] => Array
(
[0] => stdClass Object
(
[message] => bbbbbbbbb
)
[1] => stdClass Object
(
[lol] => aaaaaaaaa
)
[2] => stdClass Object
(
[message] => ccc
)
)
)
EDIT, SOLVED: so the only problem was that i didnt have message property inside of every object

Why did you think they'd be the same? The first example accesses array elements 0 and 1; the second accesses 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. Clearly at least one of those elements does not exist, given the error message you receive.
There is also a difference between print_r and echo.

Your error is because you are trying to access the object property message when it doesn't exist. Also, not an error in this case, but you are also assuming that array indexes 0-10 exist, which might not be the case.
Loop through only valid/existing array elements and check if the message property exists before accessing it:
foreach($this->facebook->my_retrieve_timeline()['data'] as $data) {
if(property_exists($data, 'message')) { // or use isset($data->message)
echo $data->message;
}
}
This doesn't make assumptions about which numeric keys exist (loops only existing elements) and also checks if message property exists before accessing it. As a bonus, it only calls my_retrieve_timeline() once instead of every loop iteration.

Related

PHP using key of one array to access same key position on another array

I've looked at a number of suggestions for this, and they seem to rely on array_combine() which unfortunately is not suitable, as they arrays need to stay separate for other functions.
The arrays are set out as per
Array ( [0] => 3 [1] => 1 [2] => 3 )
Array ( [0] => 194 [1] => 0 [2] => 452 )
When I read in the first array, I get the key as $key and everything works fine.
Whenever I try and access the second array the whole script just whites out the page.
I want the code to work simliar to this ...
$a2value = $a2[$key] => $value;
echo $a2value;
Then I can do SQL lookups using $a2value
Any help would be appreciated
Here Try this
let's suppose two arrays of same number of elements
$a1=[1,2,3];
$a2=[194,0,452];
//A Simple foreach
foreach($a1 as $key=>$a1value){
$a2value=$a2[$key];
//Perform Query here
}
Remember one thing number of elements of both array should always be equal or it will cause an error
If you aren't certain about the size of both arrays then replace the line with this code
$a2value=empty($a2[$key]) ? null : $a2[$key];
Hope this works !!!

PHP Arrays and stdClass objects

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 "[]".

How to access stdClass Multi level object or array?

I had to make a particularly complex SOAP request in PHP and seem to have received back objects within objects. I need to get a particular value for example "session_token". I can var_dump the request and even turn it in to an array but I can't access individual elements. Please help!
Objects:
stdClass Object ( [login_response] => stdClass Object
( [response_context] => stdClass Object
( [session_token] => b1043dcb82625701188ffff03572
[response_status] => OK [response_message] => Login successful
))))
Converted array:
Array ( [0] =>
Array ( [response_context] =>
Array ( [session_token] => b1043dcb82625701188ffff03572
[response_status] => OK [response_message] => Login successful
) ) )
Once it's an array, it's JUST an array, e.g.
$obj->foo->bar->baz
will simply be
$arr['foo']['bar']['baz']
So in your case
$arr[0]['response_context']['response_status'] -> "OK"
If you leave it as an object, and there is not reason not to.
echo $obj->login_response->response_context->session_token;
echo $obj->login_response->response_context->response_status;
echo $obj->login_response->response_context->response_message;
will output
b1043dcb82625701188ffff03572
OK
Login successful
Normally to access any key of an object, need to call it like this
echo $obj->key;
But, as this is a multi-level object, to access the element, you have to code like bellow.
echo $obj->login_response->response_context->session_token;
And the result will be b1043dcb82625701188ffff03572
As same, normally to access any key of an array, need to call it like this
echo $arr['key'];
But, as this is a multi-level array, to access the element, you have to code like bellow.
echo $arr[0]['response_context']['session_token'];
And the Output is b1043dcb82625701188ffff03572
Here,
0 is the key of $arr array.
response_context is the key of 0.
session_token is the key of response_context.
You can use this service, array visualizer, this will help you target and extract only what you need. Just past the print_r output in it. That's it.
Give it a try

Parse Json Object PHP

I want to parse the following Json-Object:
{"multicast_id":123456,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
I was able to succefully parse the values from success, failure, etc, but am having difficulties getting the "error"-msg ("InvalidRegistration").
I access them like this:
$b = json_decode($a, true);
if($b['success'] == 1){
$result = true;
}
How do i access the results / error section?
I tried to do it like this:
$b['results']['error']
but it didn't work.
Thank you for your help, in advance.
After you use json_decode function, a php array will be produced that will have the following structure:
Array
(
[multicast_id] => 123456
[success] => 0
[failure] => 1
[canonical_ids] => 0
[results] => Array
(
[0] => Array
(
[error] => InvalidRegistration
)
)
)
which means that in order to access the error key inside the results array you need to type $b['results'][0]['error']. Of course, this is not the optimal way unless you know that there is always going to be one index in the results array. In the case where an unknown number of indexes existed ([0], [1], [2] ... [n]), it would be a better idea to create a loop and go through each of them.

How do i get the first value or a PHP multi-demenstional array if I dont know the key?

I have this array
Array
(
[281] => Array
(
[0] => 1
[1] => 10
[2] =>
[3] =>
[4] => 1
)
)
how do i get the first element of this array if i dont know that the key is 281
i figured this would work but no go
$my_array[0]
Undefined offset
Supposed that you haven't traversed the array yet - use key() function to get the key value, and current for item value, or move pointer to the begin with reset()
var_dump(key($my_array));
var_dump(current($my_array));
Multiple methods, here is one that will work:
$output = array_slice( $inputArr, 0, 1 );
use reset(). It will give the first element but will reset the internal pointer of the array though

Categories