简体   繁体   English

通过HTTP将Android中的数组发送到PHP脚本并获取数据

[英]send an Array from Android to PHP Script over HTTP and get the data

I would like to send an integer array with 30 values Integer[] temp = new Integer[30] over HTTP (POST) to PHP an get the data in PHP again. 我想通过HTTP (POST)PHP发送一个具有30个值Integer[] temp = new Integer[30]的整数数组到PHP ,并再次在PHP获取数据。 How can I do that? 我怎样才能做到这一点? I know how to send a single value, like a string, but not how to send an array. 我知道如何发送单个值(如字符串),但不知道如何发送数组。

One way is to serialize the array in the way the php serialize command does it. 一种方法是以php serialize命令执行的方式来序列化数组。 After receiving the string value(by the method you currently use), you can use the unserialize command to get the array in your php code. 接收到字符串值(通过当前使用的方法)后,可以使用unserialize命令在php代码中获取数组。

Here is a litle php example to demonstrate the workflow. 这是一个小PHP示例,以演示工作流程。

$arr = array(1,2,3,4,5,6);

$stringArr = serialize($arr);
echo $stringArr; 
echo "<br/>";

$arr2 = unserialize($stringArr);

if ($arr === $arr2)
{
  echo "arrays are equal";
}

The output of the script is: 该脚本的输出为:

a:6:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;}
arrays are equal

The main difficulty is to construct the resulting string for complex structures (in your case, it is pretty straight forward for an array of integers). 主要困难是为复杂结构构造结果字符串(在您的情况下,对于整数数组而言,这很简单)。 This fact results in the second approach. 这一事实导致了第二种方法。

One can use a serialization API or another notation than used by the php example. 一个人可以使用序列化API或PHP示例所用的另一种表示法。 As stated by the others, JSON is one of the widespread notations. 正如其他人所说,JSON是广泛使用的表示法之一。 PHP also provides a possibility to serialize and unserialize json objects. PHP还提供了序列化和反序列化json对象的可能性。 Simply use json_decode and look at the example in the manual. 只需使用json_decode并查看手册中的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM