-1

I am trying to convert my example_data to be in the same array:

$example_data = "FirstName=Test&LastName=TestLastName&Address=ExampleSt";
$explode1 = explode('&', $example_data);

$data_array = array();
foreach ($explode1 as $values)
{
    $explode2 = explode("=", $values);

    $field_name = $explode2[0];
    $field_value =  $explode2[1];

    $data_array[] = array(
        $field_name    =>    $field_value
        );
}                

echo json_encode($data_array); 

The current output - separated arrays:

[{"FirstName":"Test"},{"LastName":"TestLastName"},{"Address":"ExampleSt"}]

The intended output I am looking for:

{"FirstName":Test,"LastName":TestLastName,"Address":ExampleSt}

Barmar
  • 741,623
  • 53
  • 500
  • 612
James
  • 3
  • 2

2 Answers2

0

In each iteration you add an array at the end of $data_array. Instead, you could just directly use $field_name as a key and $field_value as a value:

foreach ($explode1 as $values)
{
    $explode2 = explode("=", $values);

    $field_name = $explode2[0];
    $field_value =  $explode2[1];

    $data_array[$field_name] = $field_value; # Here!
}

EDIT:
As a side note, PHP has a built-in function called parse_str that can do all this heavy lifting for you:

$example_data = "FirstName=Test&LastName=TestLastName&Address=ExampleSt";
$data_array = array();
parse_str($example_data, $data_array);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

There is a function for that:

parse_str($example_data, $data_array);
echo json_encode($data_array);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87