php - 从多维数组中获取数据(foreach)

时间:2017-10-15 15:16:23

标签: php arrays multidimensional-array foreach

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

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

?>

你能帮帮我吗?

2 个答案:

答案 0 :(得分: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']
  }    
}

答案 1 :(得分:1)

那应该不是很难......

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

我猜这里解释的不多,但随时可以询问是否有任何不清楚的地方。