我有来自Facebook Graph API响应的以下数组结构。
"data": [
{
"actions": [
{
"action_type": "comment",
"value": "2"
},
{
"action_type": "offsite_conversion",
"value": "1606"
}
],
"date_start": "2017-04-03",
"date_stop": "2017-05-02"
},
{
"actions": [
{
"action_type": "post",
"value": "2"
},
{
"action_type": "post_reaction",
"value": "33"
},
{
"action_type": "page_engagement",
"value": "816"
},
{
"action_type": "post_engagement",
"value": "807"
},
{
"action_type": "offsite_conversion",
"value": "1523"
}
],
"date_start": "2017-04-03",
"date_stop": "2017-05-02"
},
]
值的数量是灵活的,我想从“offsite_conversion”获取值。通常我会这样做:
data['data'][0]['actions']['1']['value']
但在这种情况下,这不起作用,因为['1']是可变的。
答案 0 :(得分:3)
使用循环并测试操作类型。
foreach ($data['data'][0]['actions'] as $action) {
if ($action['action_type'] == 'offsite_conversion') {
$result = $data['value'];
break;
}
}
答案 1 :(得分:1)
因为" offsite_conversions"永远是最后的
如果您正在寻找$data['data'][0]['actions'][LAST VALUE]['value']
:
您对计数的想法应该有效:
$actions = $data['data'][0]['actions'];
$index = count($actions) - 1;
$value = $actions[$index]['value'];
答案 2 :(得分:0)
所以不完全清楚你想要实现什么,但是以一种简单的方式你可以迭代你的$needed_values = array();
foreach ($data['data'] as $item) {
foreach ($item['actions'] as $action) {
if ($action['action_type'] == 'offsite_conversion') {
$needed_values[] = $action['value'];
}
}
}
数组:
socket = new Socket(serverAddr, Integer.parseInt(server_port.getText().toString()));
答案 3 :(得分:0)
假装$json
保存来自facebook的数据
<?php
$data = json_decode($json);
$conversions = 0;
foreach ($data as $datum) {
foreach ($datum['actions'] as $action) {
if ($action['action_type'] === 'offsite_convserion') {
$conversions += (int)$action['value'];
break;
}
}
}
答案 4 :(得分:0)
Barmar是最好的方法,但如果你想要最后一个,它会更容易:
$result = end($data['data'][0]['actions'])['value'];