Anyone know how to do this?
I’m trying to loop through an array where not every object has a value. What I’d like to get is an array where the key holds the number that specifies the stdClass Object and has “value” as value. If there is no “value” specified “0” should be printed.
So the final array should look something like this:
Array (
[123456789_123456789] => 192
[54321_98765] => 0
[987654321_123456789] => 1292
[987854321_123456734] => 0
)
Here is the original output:
stdClass Object (
[123456789_123456789] => stdClass Object (
[data] => Array (
[0] => stdClass Object (
[id] => 123456789_123456789/insights/name_of_metric/period
[name] => name_of_metric
[period] => lifetime
[values] =>
Array (
[0] => stdClass Object (
[value] => 1292 )
)
[title] => Lifetime Post Organic Reach
[description] => A Description ...
[paging] => stdClass Object (
[previous] => https://graph.facebook.com/ALINK
[next] => https://graph.facebook.com/ALINK
) )
[54321_98765] => stdClass Object (
[data] => Array (
[paging] => stdClass Object (
[previous] => https://graph.facebook.com/ALINK
[next] => https://graph.facebook.com/ALINK
))
[987654321_123456789] => stdClass Object (
[data] => Array (
[0] => stdClass Object (
[id] => 987654321_123456789/insights/name_of_metric/period
[name] => name_of_metric
[period] => lifetime
[values] =>
Array (
[0] => stdClass Object (
[value] => 1292 )
)
[title] => Lifetime Post Organic Reach
[description] => A Description ...
[paging] => stdClass Object (
[previous] => https://graph.facebook.com/ALINK
[next] => https://graph.facebook.com/ALINK
))
[987854321_123456734] => stdClass Object (
[data] => Array (
[paging] => stdClass Object (
[previous] => https://graph.facebook.com/ALINK
[next] => https://graph.facebook.com/ALINK
))
)
This is what I tried so far:
$aVar = array();
foreach ($var as $var_1){
foreach ($var_1->data as $var_2 ){
foreach ($var_2->values as $var_3){
$aVar[] = $var_3->value;
}
}
}
I believe I have to use foreach (var_1->data as $var_2 => $var2_1)
The isset() “language construct” and is_array() function are your friend in this scenario, unless you are having another problem not specified, your problem is not very clear 😉
What you need to do is change your outer for-each loop to something similar to the following, with additional validation within:
This code is untested, I don’t believe I have made any syntactical errors.