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 用matlab求微分方程初值问题
  • ¥15 vscode下编写第三方库opencv与pcl代码时没有代码提示
  • ¥15 能够跑通不报错,如何解决?(标签-matlab)
  • ¥15 MOS在RDS较大,频率高时开关波形异常
  • ¥15 SCENIC分析报错求解答
  • ¥15 ceph初始化mon不成功 下图不报错 这个是什么元
  • ¥15 数学建模数学建模少ai
  • ¥35 这个等效电路图是什么意思?(答疑)(有没有不是chat的,我就是在chat搜不到才来问的,chat还开了VIP)(可以追加酬金)
  • ¥200 基于同花顺supermind的量化策略脚本编辑
  • ¥15 黄永刚的晶体塑性子程序中输入的材料参数里的晶体取向参数是什么形式的?