Mikkel Mikkel - 1 month ago 12
MySQL Question

Add data to each element in array -> JSON

I am extracting data from a MySQL database into an assoc array.

I need to add an additional row of data, topicstring, to each element in the array, then convert to JSON.

But for some reason, I can only get it to add the additional rows to the first element in the array, or as a new, final element in the array.

Code:

$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);
}

Answer

This might help:

$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);