【问题标题】:php - Getting Data from multi dimensional array (foreach)php - 从多维数组(foreach)中获取数据
【发布时间】:2017-10-15 15:16:23
【问题描述】:

我有一个多维数组,如下所示:

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
                        )

                )

        )

)

我想在第二级(0、1、2)获取每个数组的 update_id、id、first_name 和文本。然后我想对这个变量做点什么。

我已经在其他线程中搜索,但无法正常工作。

<?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");

?>

你能帮帮我吗?

【问题讨论】:

  • 数组中的必填字段是什么
  • 数组始终采用与上图相同的格式。我从 Telegram bot API (getUpdates) 自动获取它。我想访问以下字段:update_id、id、first_name、text

标签: php arrays multidimensional-array foreach


【解决方案1】:

类似于您尝试的foreach 循环:

$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'];
    }
  }
}

然后您可以使用以下方式访问聊天值:

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

以下是您的 foreach 循环如何工作的说明:

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

现在您可以通过以下方式访问您的值:

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

【讨论】:

    【解决方案2】:

    这应该不难......

    $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']
        ];
    }
    

    我想这里没有太多解释,但如果有什么不清楚的地方,请随时询问。

    【讨论】:

      猜你喜欢
      • 2019-11-04
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      • 2017-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多