I have a MySQL database, the content of which I need to serve as a JSON feed. It is a list of parameters, which have two set of attributes, Source and Target, with again have a set of attributes. I need the following structure:
Parameter: [
Source: {
operation: xxx,
fc: xxx,
address: xxx
}
Target: {
topic: xxx
}
],[
I'll admit I am weak in dealing with arrays in PHP, and I am at my wits end. My code looks like so:
class Parameter {
public $parameter = "";
}
class Join {
public $Source = "";
public $Target = "";
}
class Source {
public $sourceOperation = "";
public $fc = "";
public $address = "";
}
class Target {
public $topic = "";
public $targetOperation = "";
}
//Then we get the correct registers from the database
$sql_build_profile="SELECT * FROM DeviceProfiles WHERE DeviceID = '".$q."' AND RegisterID IN (".$ParameterArray.") ORDER BY RegisterID ASC";
$result_build_profile = mysqli_query($con,$sql_build_profile);
//Time to build the output
while($row1 = mysqli_fetch_array($result_build_profile)) {
$targetString = $UniqueString."/".$row1['RegisterID'];
$source = new Source();
$source->sourceOperation = $row1['SourceOperation'];
$source->fc = $row1['FC'];
$source->address = $row1['Register'];
$target = new Target();
if ($row1['SourceOperation'] == "Write"){
$target->targetOperation = "subscribe";
} else {
$target->targetOperation = "";
}
$target->topic = $targetString;
$join = new Join();
$join->Source = $source;
$join->Target = $target;
$parameter = new Parameter();
$parameter->parameter = $join;
echo ($i>0?',':'').json_encode($parameter, JSON_PRETTY_PRINT);
}
which gets me this JSON output:
"parameter": {
"Source": {
"sourceOperation": "Read",
"fc": "3",
"address": "16383"
},
"Target": {
"topic": "09265eb2455845552e4df3c9a20a8eed\/1",
"targetOperation": ""
}
}
}{
"parameter": {
"Source": {
"sourceOperation": "Write",
"fc": "16",
"address": "16383"
},
"Target": {
"topic": "09265eb2455845552e4df3c9a20a8eed\/2",
"targetOperation": "subscribe"
}
}
}
missing the single leading "[]" and ",". I am quite sure it's to do with making an array out of the data, but I can't figure it out. I've looked at other questions, but not been able to apply them to my example - likely due to limited understanding.
Thanks for you help.