【问题标题】:Passing String Arrays into PHP file with Android使用 Android 将字符串数组传递到 PHP 文件中
【发布时间】:2017-03-03 05:34:50
【问题描述】:

我正在尝试使用改造和 PHP 在 MySQL 中存储值。我将向 PHP 传递一个 postid 字符串 (postid) 和一个字符串数组。对于字符串数组中的每个索引(称为标签),我将在数据库中创建一个唯一的行。它将具有以下形式:

--------------------
|postid    |  tags  |
--------------------
| postid   | tags[0]|
| postid   | tags[1]|
| postid   | tags[2]|
....................
--------------------

我遇到的问题是,对于字符串数组,只存储了数组中的最后一个值。

这是改造界面

@FormUrlEncoded
@POST("create_recipe.php")
Call<Void> createRecipe(
        @Field("postid") String postid,
        @Field("tags") String[] tags
);

和改造客户电话

Retrofit retrofit = ApiClient.getClient();
                                ApiInterface apiService = retrofit.create(ApiInterface.class);

                                Call<Void> call = apiService.createRecipe(postid, tags);
                                call.enqueue(new Callback<Void>() {
                                    @Override
                                    public void onResponse(Call<Void> call, Response<Void> response) {

                                    }

                                    @Override
                                    public void onFailure(Call<Void> call, Throwable t) {

                                    }
                                });

这是处理这个问题的 PHP 的样子(不包括一些初始化代码)

if (isset($_POST['postid']) && isset($_POST['tags']){
$uid = $_POST['postid'];
$tags = array($_POST['tags']);  
$tags_new = str_replace(array('[', ',', ']'), '' , $tags);

foreach ($tags_new as $value){
          mysql_query("INSERT INTO Tags(postid, tag) VALUES('$postid', '$value')");
}

}

如果我传入 postid = 30 和 tags = {"milk", "cheese", "bread"} 我希望它看起来像

--------------------
|postid    |  tags  |
--------------------
| 30   | milk      |
| 30   | cheese    |
| 30   | bread     |
....................
--------------------

但只会存储面包。

如何处理PHP中作为参数传入的字符串数组?

当我将数组传递给 $tags 时,数组的形式是什么?

【问题讨论】:

    标签: php android mysql database retrofit


    【解决方案1】:

    前段时间我遇到了同样的问题,但没有找到明确的解决方案。但是,我为类似的东西构建了一个简单的解决方案。我希望this solution 有所帮助。

    【讨论】:

      【解决方案2】:

      其实你可以在PHP工作表中打印出来,你可以在此处添加以下内容来记录输入。

      file_put_contents("test.log",json_encode($_POST)."--".json_encode($_GET));
      

      只有这样,您才能确定数组是否正确传递给 php 脚本。

      【讨论】:

        【解决方案3】:

        您可能需要重新考虑这一点,因为以下行基本上只是删除了字符串中的所有障碍($tags,现在被解释为字符串而不是数组):

        $tags_new = str_replace(array('[', ',', ']'), '' , $tags);
        

        改成

        $tags_new = split(',' , $tags);

        【讨论】:

        • 谢谢。只是出于好奇,你知道传入PHP时String数组的形式是什么吗?
        • 我会尝试像您在下面显示的那样调试它以找到表单。
        猜你喜欢
        • 2015-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-15
        • 2022-11-26
        • 2017-11-14
        • 1970-01-01
        相关资源
        最近更新 更多