Malawirel
Malawirel

Reputation: 115

php - Getting Data from multi dimensional array (foreach)

I have a multidimensional array that looks like the one below:

Array
(
    [ok] => 1
    [result] => Array
        (
            [0] => Array
                (
                    [update_id] => 1001
                    [message] => Array
                        (
                            [message_id] => 3
                            [from] => Array
                                (
                                    [id] => 123
                                    [is_bot] => 
                                    [first_name] => John
                                    [last_name] => Doe
                                    [username] => JohnDoe
                                    [language_code] => de-DE
                                )

                            [chat] => Array
                                (
                                    [id] => 123
                                    [first_name] => John
                                    [last_name] => Doe
                                    [username] => JohnDoe
                                    [type] => private
                                )

                            [date] => 1508065616
                            [text] => Hello
                        )

                )

            [1] => Array
                (
                    [update_id] => 1002
                    [message] => Array
                        (
                            [message_id] => 4
                            [from] => Array
                                (
                                    [id] => 456
                                    [is_bot] => 
                                    [first_name] => Jane
                                    [language_code] => de-DE
                                )

                            [chat] => Array
                                (
                                    [id] => 456
                                    [first_name] => Jane
                                    [type] => private
                                )

                            [date] => 1508067033
                            [text] => /start
                            [entities] => Array
                                (
                                    [0] => Array
                                        (
                                            [offset] => 0
                                            [length] => 6
                                            [type] => bot_command
                                        )

                                )

                        )

                )

            [2] => Array
                (
                    [update_id] => 1003
                    [message] => Array
                        (
                            [message_id] => 5
                            [from] => Array
                                (
                                    [id] => 456
                                    [is_bot] => 
                                    [first_name] => Jane
                                    [language_code] => de-DE
                                )

                            [chat] => Array
                                (
                                    [id] => 456
                                    [first_name] => Jane
                                    [type] => private
                                )

                            [date] => 1508067035
                            [text] => Hi
                        )

                )

        )

)

I want to get the update_id, the id, the first_name and the text of each of these arrays at the second level (0, 1, 2). Then I want to do something with this variables.

I was searching already in other threads but couldn't get it working right.

<?php

// First I am getting the messages from my Telegram bot
$botToken = "mySecretBotToken"; // removed the token for security reasons here
$website = "https://api.telegram.org/bot".$botToken;
$update = file_get_contents($website."/getUpdates");
$updateArray = json_decode($update, TRUE);

// For testing I was getting here the chatID of the first message
$chatID = $updateArray["result"][0]["message"]["chat"]["id"];

// Please ignore this. Here I was trying around a little bit with foreach
$newArray = array();
$i = 0;
foreach ($updateArray as $key => $value) {
 if (is_array($value)) {
   $newArray[$i] = array();
  foreach ($value as $k => $v) {
    $newArray[$i][] = $v;
  }
  $i++;
 }
}

// Printing the chatID for test purposes and replying to the message
print_r($chatID);
file_get_contents($website."/sendmessage?chat_id=".$chatID."&text=test");

?>

Can you please help me?

Upvotes: 0

Views: 641

Answers (2)

bloodyKnuckles
bloodyKnuckles

Reputation: 12079

Similar to the foreach loop you tried:

$newArray = array();
foreach ($updateArray as $key => $value) {
  if (is_array($value)) {
    foreach ($value as $k => $v) {
      $newArray[$k]               = array();
      $newArray[$k]['update_id']  = $v['update_id'];
      $newArray[$k]['id']         = $v['message']['chat']['id'];
      $newArray[$k]['first_name'] = $v['message']['chat']['first_name'];
      $newArray[$k]['text']       = $v['message']['text'];
    }
  }
}

Then you can access the chat values using:

foreach ( $newArray as $chat_info ) {
  print_r($chat_info['id']);
  file_get_contents(
    $website."/sendmessage?chat_id=".$chat_info['id']."&text=test"
  );
  // $chat_info['update_id']
  // $chat_info['first_name']
  // $chat_info['text']
}

Here's an explanation how YOUR foreach loop works:

$newArray = array();
$i = 0;
foreach ($updateArray as $key => $value) {
  // $updateArray keys are ['ok' (not array), 'result' (array)]

  if (is_array($value)) { // only 'result' passes this test
    $newArray[$i] = array(); // this only happens once

    foreach ($value as $k => $v) { // loop over 'result'
      // 'result' keys are [0, 1, 2]

      $newArray[$i][] = $v; 
      // $newArray[0][0] = $v (first loop)
      // $newArray[0][1] = $v (second loop)
      // $newArray[0][2] = $v (third loop)
    }
    $i++; // this only happens once
  }
}

Now you can access your values with:

foreach ( $newArray as $value ) { // only one value in the sample, key: 0
  foreach ( $value as $chat_info ) { // 3 values in the sample, keys: 0, 1, 2

    print_r($chat_info['message']['chat']['id']);
    file_get_contents(
      $website."/sendmessage?chat_id=" . $chat_info['message']['chat']['id'] . "&text=test"
    );

    // $chat_info['update_id']
    // $chat_info['message']['chat']['first_name']
    // $chat_info['message']['text']
  }    
}

Upvotes: 1

Pevara
Pevara

Reputation: 14310

That shouldn't be to hard...

$output = [];
foreach ($updateArray['result'] as $update) {
    $output[] = [
        'update_id' => $update['update_id'], 
        'id' => $update['message']['from']['id'], 
        'first_name' => $update['message']['from']['first_name'], 
        'text' => $update['message']['text']
    ];
}

Not very much to explain here I guess, but feel free to ask if anything is unclear.

Upvotes: 1

Related Questions