【问题标题】:php key in array being changed数组中的 php 键被更改
【发布时间】:2013-12-31 03:58:18
【问题描述】:

我有一个奇怪的问题,一旦我提交了一个代码数组,它似乎丢失了它的密钥。

    $data = array(
    'title' => array(
         'en' => 'en test',
         'fr' => 'fr test'
        ),
    'description' => array(
         'en' => 'description en',
         'fr' => 'description fr'
        ),
    );



try {
    $oauth = new OAuth("xxx","xxx",OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION);
    $oauth->setToken("xxx","xxx");

    // first output of array
    echo '<pre>',print_r($data),'</pre>';

    $oauth->fetch("http://foobar.com/rest/v1/", $data, OAUTH_HTTP_METHOD_POST , array('Content-Type' => 'application/x-www-form-urlencoded'));

    // second output of array
    echo '<pre>',print_r($data),'</pre>';

    $response_info = $oauth->getLastResponseInfo();
    header("Content-Type: {$response_info["content_type"]}");
    echo $oauth->getLastResponse();

    //print_r($oauth);
} catch(OAuthException $E) {
    print_r($E);
    echo "Exception caught!\n";
    echo "Response: ". $E->lastResponse . "\n";
}

生成的输出

// first output of array
Array
(
    [title] => Array
        (
            [en] => en test
            [fr] => fr test
        )

    [description] => Array
        (
            [en] => description en
            [fr] => description fr
        )

)
1
// second output of array
Array
(
    [title] => Array
        (
            [0] => fr test
            [1] => en test
        )

    [description] => Array
        (
            [0] => description fr
            [1] => description en
        )

)

如您所见,一旦数据被传递,数组就会发生变化。

查看发送到服务器的 headers,post 数据看起来像

title=fr%20test&title=en%20test&description=description%20fr&description=description%20en

服务器端的 api 似乎不接受任何东西,所以我认为问题可能与发送数组的方式有关。

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    这可能是由于许多问题,很可能您的 $data 变量作为对您的 oAuth 库的引用传递,并且该库可能会执行排序而不是 asort 或 array_merge,这将从数组中删除键!

    可以肯定的是,造成这种情况的绝对是 oAuth 库。您只需执行以下操作即可复制数据:

    $oauth->fetch("http://foobar.com/rest/v1/", $copy = $data, OAUTH_HTTP_METHOD_POST , array('Content-Type' => 'application/x-www-form-urlencoded'));
    

    这会将数组复制到 $copy 并保持您的 $data 完整。不过,您可能想检查一下它为什么会改变数据!

    编辑

    是排序,看数据,是在第二个var_dump中排序的!逆序排序,但是排序好了!

    【讨论】:

      猜你喜欢
      • 2021-09-10
      • 1970-01-01
      • 2014-06-14
      • 1970-01-01
      • 2017-09-20
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      相关资源
      最近更新 更多