0

I'm trying to encode 2 name/value pairs in a JSON object within a JSON array. At the moment I am able to encode the name/value pairs but each one goes in as a separate object within the array.

Here is my code:

    if ($tag == "getLatLng")
    {
        $lineNumber = $_GET['lineNumber'];
        $coordinates = $db->getCoOrds($lineNumber);

        if ($coordinates != false)
        {
            //Get data and set success = 1
            $response["success"] = 1;
            $response['coordinates'] = array();

            $arrayLength = count($coordinates);

            foreach ($coordinates as $value)
            //for ($i=0; $i<$arrayLength+1; $i++)
            {
                //echo $i;
            $response["coordinates"][]['latitude'] = $value[0];
            $response["coordinates"][]['longitude'] = $value[1];
            //$response["coordinates"][]['longitude'] = $coordinates[$i];
            }
            echo json_encode($response);
        }

This is a sample output:

    {"success":1,"error":0,"coordinates":[{"latitude":"00.000000"},{"longitude":"-00.000000"},{"latitude":"00.000000"},{"longitude":"-00.000000"},{"latitude":"00.000000"},{"longitude":"-00.000000"}]}

But I need this:

    {"success":1,"error":0,"coordinates":[{"latitude":"00.000000","longitude":"-00.000000"},{"latitude":"00.000000","longitude":"-00.000000"},{"latitude":"00.000000","longitude":"-00.000000"}]}

Thanks for your help!

1 Answer 1

2

Try this

 $i=0;
foreach ($coordinates as $value)
        //for ($i=0; $i<$arrayLength+1; $i++)
        {

        $response["coordinates"][$i]['latitude'] = $value[0];
        $response["coordinates"][$i]['longitude'] = $value[1];
        $i++;
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thankyou, works perfect. Can you explain to me what this does please?
Sure. When you use $response["coordinates"][]['latitude'] an incremented value is assigned to the empty key, so if you repeat it, every time it will get an incremented value and makes it as $response["coordinates"][0]['latitude'] $response["coordinates"][1]['longitude'] Hope it is clear now.
sorry I am new to stackoverflow can't get hold of the formatting yet :)
@ThinkDifferent Put your code in between backticks. (The ones next to the 1) Like this: $response["coordinates"][]['latitude']
@ThinkDifferent No worries, just a tip though, the help button is there for a reason, it contains the comment 'mini-Markdown' formatting.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.