1
私はphpに新しく、2つの配列を1つのJSONオブジェクトにエンコードしようとしています。json_encode複数の配列をPHPの1つのJSONオブジェクトに挿入しますか?
現在、これはJSON出力です:
{
"image_link": "some url",
"zoomin_level": "8",
"zoomout_level": "18.5",
"position_lat": "32.913105",
"position_long": "-117.140363",
}
私は何を達成したいことは以下の通りです:
{
"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
}
}
}
これは、ここで尋ねた質問に似ています:PHP json_encode multiple arrays into one object
しかし鉱山私は2番目の配列を1番目の配列の中にキーと値の部分の一部として追加するのが好きなので少し違っています。
はここに私のPHPコードです:
$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);
は、適切な構文を知らない、私はゴミの結果、以下を実行しようとしました:
echo json_encode($newArray, "locations" =>$locations);
PERFECT ..それが可能なときに答えを受け入れるでしょうか? – Pangu
最後の質問ですが、自動生成された値 '1'、' 2'をそれぞれの項目に対してユニークな文字列に変更する方法はありますか? 'locat ion1'、 'location2'? – Pangu
あなたは$ indexnewを使用しています。これはカウンタで、1,2、などが得られます。$ indexnewの代わりに、必要なものを使います。例えば。 $ locations ['location_1'] =配列( "image_link" => ....) – Phil