dsj8000 2016-12-22 22:24
浏览 57
已采纳

json_encode将多个数组编译成PHP中的一个JSON对象?

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条回答 默认 最新

  • douyu9433 2016-12-22 22:27
    关注

    Try:

    $newArray['locations'] = $locations;
    echo json_encode ($newArray);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan