从数组响应中获取数据

时间:2016-11-03 12:48:10

标签: php arrays object

我的回复如下。

array:4 [▼
   "response-1" => Data {#280 ▶}
   "response-2" => Exception {#235 ▼
                     #errors: array:1 [▶]
                       #message: "{"error":{"errors":[{"domain":"global","reason":"insufficientPermissions","message":"User does not have sufficient permissions for this data."}],"code":403,"message":"User does not have sufficient permissions for this data."}}"
   "response-3" => Data {#280 ▶}
   "response-4" => Data {#280 ▶}
]

现在,我只需要获取Data部分,而Exception部分不会受到PHP中的响应的影响。我真的不知道如何通过它,但我确实尝试过这样的事情:

if(!$results['response-'. $id] == 'Exception'){
      //do something
}

2 个答案:

答案 0 :(得分:1)

由于数组由其他数组组成,最简单的方法是迭代数组中的每个元素,并在每个元素的Data键中提取值。

这假设你的数组看起来像这样:

$arr = [
    "response-1" => ["Data" => ["some other array or object here"]],
    "response-2" => ["Exception" => ["some other array or object here"]],
    "response-3" => ["Data" => ["some other array or object here"]],
    "response-4" => ["Data" => ["some other array or object here"]],
];

然后获取所有Data部分看起来像这样......

foreach($arr as $part) {
    if (isset($part["Data"])) {
        // Do something with $part["Data"] here
        var_dump($part["Data"]); // e.g.
    }
}

输出

array(1) {
  [0]=>
  string(31) "some other array or object here"
}
array(1) {
  [0]=>
  string(31) "some other array or object here"
}
array(1) {
  [0]=>
  string(31) "some other array or object here"
}

答案 1 :(得分:0)

将所有Data值放入数组的最简单方法:

$data = array_column($results, 'Data');

如果那些实际上是对象,那么:

$data = array_map(function($v) { return $v->Data; }, $results);