-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}

2
  • data_array[$field_name] = $field_value; Commented Dec 12, 2020 at 22:19
  • 1
    Are you looking for this? php.net/manual/en/function.parse-str.php Commented Dec 12, 2020 at 22:22

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

There is a function for that:

parse_str($example_data, $data_array);
echo json_encode($data_array);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.