1

I'm new to php and am trying to encode 2 arrays together into one JSON object.

Currently this is the JSON output:

{
    "image_link": "some url",
    "zoomin_level": "8",
    "zoomout_level": "18.5",
    "position_lat": "32.913105",
    "position_long": "-117.140363",
}

What I like to achieve is the following:

{
    "image_link": "some url",
    "zoomin_level": "2",
    "zoomout_level": "15",
    "position_lat": "32.9212",
    "position_long": "-117.124",

    "locations": {
        "1": {
            "image_link": "some url",
            "name": "Name",
            "lat": 32.222,
            "marker_long": -112.222
        },
        "2": {
            "image_link": "some url",
            "name": "Name",
            "lat": 32.222,
            "marker_long": -112.222
        }
    }
}

This is similar to the question asked here: PHP json_encode multiple arrays into one object

However mine is a bit different because I like to add the 2nd array as part of a key-value part within the 1st array.

Here's my php code:

$sql = "select * from first_table";
$result = mysqli_query($connection, $sql) or die("Error in Selecting "    . mysqli_error($connection));

$rowCount = $result->num_rows;
$index = 1  ;
$newArray = [];
while($row =mysqli_fetch_assoc($result))
{
    $sqlnew = "select * from second_table";
    $resultnew = mysqli_query($connection, $sqlnew) or die("Error in Selecting " . mysqli_error($connection));

    //create an array
    $jsonData = array();
    $rowCountnew = $resultnew->num_rows;
    $indexnew = 1;

    if ($rowCountnew >0)
    {
        while($rownew =mysqli_fetch_assoc($resultnew))
        {
            $locations[$indexnew] = array("image_link" => $rownew['image_link'], "name" => $rownew['name'], "position_lat" => doubleval($rownew['position_lat']), "position_long" => doubleval($rownew['position_long']) );

            ++$indexnew;

        }   
    }
    $newArray[$row['map_type']] = $row['map_value'];
}

echo json_encode($newArray);

Not knowing the proper syntax, I tried to perform the following which resulted in garbage: echo json_encode($newArray, "locations" =>$locations);

1 Answer 1

3

Try:

$newArray['locations'] = $locations;
echo json_encode ($newArray);
Sign up to request clarification or add additional context in comments.

2 Comments

one last question, is there any way to change the auto-generated values 1, 2, for each item to be a unique string instead, say location1, location2?
You're using $indexnew, which is a counter and is why you're getting 1, 2, etc. Instead of $indexnew, use whatever you want. eg. $locations['location_1'] = array("image_link" => ....)

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.