dpl74687 2014-07-26 14:37
浏览 44
已采纳

具有关联数组的array_push导致多维数组

I have the following function which does some stuff and returns an array:

  1. function do_work($array){
  2. $result = array();
  3. array_push($result, array("HAHAHAH" => "looooooool"));
  4. foreach($array as $key=>$val){
  5. array_push($result, array($key => $val));
  6. }
  7. return $result;
  8. }

I originally call this and pass the $_GET array in it. What I expect at the end is a flat JSON object. But this returns a JSON array instead:

in my calling code:

  1. $array = do_work($_GET);
  2. echo json_encode($array);

if I give the function following GET array:

handler.php?action=register_new_user&shit=happens

This will be the result, but I want it to be a flat JSON not an array:

[{"HAHAHAH":"looooooool"},{"action":"register_new_user"},{"shit":"happens"}]
  • 写回答

1条回答 默认 最新

  • dszsajhd237437 2014-07-26 14:43
    关注

    array_push pushes the contents onto the end of the array, and you're pushing an array onto the end of an array, meaning you're creating a multi dimensional array.

    If you want to merge two arrays, use array_merge or set the value directly if it's a single value:

    1. $foo = array('one' => 1, 'two' => 2);
    2. $bar = array('three' => 3, 'four' => 4);
    3. $foobar = array_merge($foo, $bar);
    4. // otherwise
    5. $foo['three'] = 3;
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部