-1

I have found a solution, however, I am looking for a better one. Here is a situation:

I am sending a request with the following code.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));
$result = curl_exec($ch); # Here I am receiving a response.

if ($result === FALSE) {
    die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);

Now, the $result is the response that I have received and I want to read it. It is in JSON format. Looks like this:

{
  "multicast_id": 1234567890,
  "success": 0,
  "failure": 10,
  "canonical_ids": 0,
  "results": [
    {
      "error": "InvalidRegistration"
    },
    {
      "error": "InvalidRegistration"
    },
    {
      "error": "InvalidRegistration"
    },
    {
      "error": "InvalidRegistration"
    },
    {
      "error": "InvalidRegistration"
    },
    {
      "error": "InvalidRegistration"
    },
    {
      "error": "InvalidRegistration"
    },
    {
      "error": "InvalidRegistration"
    },
    {
      "error": "InvalidRegistration"
    },
    {
      "error": "InvalidRegistration"
    }
  ]
}

At first I tried parsing it using json_decode($result) but that got me an error, so I tried to parse it as array of elements with json_decode($result, true) which worked just fine.

Now, I don't need any other information besides results[] array with all the errors in that particular order.

So I was able to get it with the following code:

$responses = array();
$decoded = json_decode($result, true);
foreach ($decoded as &$item) {
  # During first iteration, in order to find array of "results" I have to perform this check
    if (is_array($item)) {
        foreach ($item as &$in_item) {
            foreach ($in_item as &$in_in_item) {
              $responses[] = $in_in_item;
            }
        }
     }
}

With this kind of iteration through multiple arrays I was able to get all the "InvalidRegistration" messages and then use them for my needs.

This solution works of course, however, I was wondering if there a better, more concise way of achieving same result.

DarkBee
  • 16,592
  • 6
  • 46
  • 58
Vitaliy-T
  • 733
  • 6
  • 23

1 Answers1

3

You don't need to iterate to get InvalidRegistration. just take the results in an array to get InvalidRegistration errors.

$decoded = json_decode($result, true);

$invalidRegistration = $decoded['results'];
var_dump ( $invalidRegistration ); 
Al-Amin
  • 596
  • 3
  • 16