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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?