-2

I need to write a foreach using these user's ids:

The array that the API returns:

{"users":[{"id":"14"},{"id":"19"}]}

I want to send a mail based on each user id, thats why I need a foreach statement. How do I do that?

Emma
  • 27,428
  • 11
  • 44
  • 69
Héctor A
  • 69
  • 1
  • 9
  • 3
    Please at least give it a go and show us your attempt. `json_decode` and `foreach` will help you here. – Matt May 19 '19 at 02:38
  • I'm using Pusher's api for websockets. And the returning value of a channel's connection is: $response[ 'body' ] = {"users":[{"id":"14"},{"id":"19"}]} i don't have experience getting array's values on a foreach – Héctor A May 19 '19 at 02:41
  • 1
    Then read the manual on foreach and if you get stuck come back again – Andreas May 19 '19 at 02:42
  • Already did, i just need to get those user's ids, but thanks – Héctor A May 19 '19 at 03:08

1 Answers1

1

Maybe, here we could first json_decode, then loop through the users and append a username maybe using id values to the array:

$str = '{"users":[{"id":"14"},{"id":"19"}]}';

$array = json_decode($str, true);
foreach ($array["users"] as $key => $value) {
    $array["users"][$key]["username"] = "user_" . $value["id"];
}

var_dump($array);

Output

array(1) {
  ["users"]=>
  array(2) {
    [0]=>
    array(2) {
      ["id"]=>
      string(2) "14"
      ["username"]=>
      string(7) "user_14"
    }
    [1]=>
    array(2) {
      ["id"]=>
      string(2) "19"
      ["username"]=>
      string(7) "user_19"
    }
  }
}
Emma
  • 27,428
  • 11
  • 44
  • 69
  • 1
    Thank you! i did this: $str = '{"users":[{"id":"14"},{"id":"19"}]}'; $array = json_decode($str, true); foreach ($array["users"] as $key => $value) { echo $value['id']; } And the output was the user's ids, it worked – Héctor A May 19 '19 at 03:33