-1

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"}]
Valentin Mercier
  • 5,256
  • 3
  • 26
  • 50
Dumbo
  • 13,555
  • 54
  • 184
  • 288
  • 1
    Actually this is to be expected as you push a new value. If you want to set the key, what's wrong with a solution like [`$result['foo'] = 'bar';`](http://de2.php.net/manual/en/function.array-push.php#108118)? – kero Jul 26 '14 at 22:42

1 Answers1

2

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;
MatsLindh
  • 49,529
  • 4
  • 53
  • 84