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

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

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

function do_work($array){ 
      $result = array();

      array_push($result, array("HAHAHAH" => "looooooool"));

      foreach($array as $key=>$val){
          array_push($result, array($key => $val));
      }

      return $result;
}

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:

$array = do_work($_GET);
 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 22: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:

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

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮