简体   繁体   English

从数组响应中获取数据

[英]fetch data from array response

I've response as below.我的回应如下。

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 ▶}
]

Now, I need to fetch only Data part leaving the Exception part untouched from response in PHP.现在,我只需要获取Data部分,而不会从 PHP 的响应中获取Exception部分。 I don't really know how to get through it but I did try something like this:我真的不知道如何通过它,但我确实尝试过这样的事情:

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

Since the array is made up of other arrays, the simplest approach is to just iterate over each element in the array and extract the values in the Data key of each element.由于数组由其他数组组成,因此最简单的方法是遍历数组中的每个元素并提取每个元素的Data键中的值。

This assumes that your array looks something like this:这假设您的数组如下所示:

$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"]],
];

Then getting all the Data parts would look something like this...然后获取所有Data部分看起来像这样......

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

output输出

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"
}

The simplest way to get all of the Data values into an array:将所有Data值放入数组的最简单方法:

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

If those are actually objects, then:如果这些实际上是对象,那么:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM