我正在从MySQL数据库中提取数据到assoc数组中。

我需要向数组中的每个元素添加另一行数据topictopic,然后转换为JSON。

但是由于某种原因,我只能将其添加到行中的第一个元素,或者作为数组中新的最终元素。

码:

$sql_build_profile="SELECT SourceOperation, FC, Register, RegisterID FROM DeviceProfiles WHERE DeviceID = '".$q."' AND RegisterID IN (".$ParameterArray.") ORDER BY RegisterID ASC";
$result_build_profile = mysqli_query($con,$sql_build_profile);
$json_array = array();
//Time to build the output
while($row1 = mysqli_fetch_assoc($result_build_profile)) {

$topicString = $UniqueString."/".$row1['RegisterID'];
$json_array[] = $row1;
foreach ($result_build_profile as $key => $result_build_profile) {
    $result_build_profile[$key]['topic'] = $topicString;
}
echo json_encode($result_json);
}

最佳答案

这可能会有所帮助:

$sql_build_profile="SELECT SourceOperation, FC, Register, RegisterID FROM DeviceProfiles WHERE DeviceID = '".$q."' AND RegisterID IN (".$ParameterArray.") ORDER BY RegisterID ASC";
$result_build_profile = mysqli_query($con,$sql_build_profile);

$json_array = array();

//Time to build the output
while($row1 = mysqli_fetch_assoc($result_build_profile)) {

    $topicString = $UniqueString."/".$row1['RegisterID'];
    $row1['topic'] = $topicString;

    $json_array[] = $row1;
}

echo json_encode($json_array);

09-27 18:50