任何人都知道如何做到这一点?多维数组循环与一些值未设置 - PHP
我想通过一个数组,其中不是每个对象都有一个值。我想得到的是一个数组,其中的键保存了指定stdClass对象的数字,并将“value”作为值。如果没有指定“值”,则应打印“0”。
所以最后阵列应该是这个样子:
Array (
[123456789_123456789] => 192
[54321_98765] => 0
[987654321_123456789] => 1292
[987854321_123456734] => 0
)
原来这里是输出:
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
))
)
这是我试过到目前为止:
$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;
}
}
}
我相信我必须使用foreach (var_1->data as $var_2 => $var2_1)
你到目前为止尝试过什么?你在这样做的过程中遇到了具体问题?什么阻碍你只是检查这个值,例如? – hakre 2012-03-12 21:42:44
你需要循环的逻辑吗?要省略空对象,只需使用is_null或is_set,如果值为null,则将值设置为0,否则复制该值。 – evanmcdonnal 2012-03-12 21:44:36
到目前为止,你的循环是什么样的? – jeroen 2012-03-12 21:44:39