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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?