Reputation: 595
I have this code:
function setWeek($week) {
preg_match_all("/[\d\/]+/", $week, $output, PREG_SET_ORDER, 0);
$this->week = array("week" =>
array('id' => $output[0][0], "start" => $output[1][0], "end" => $output[2][0]));
$json = json_encode($this->week);
echo $json;
}
It returns me this:
{"week":{"id":"247","start":"12\/04\/18","end":"19\/04\/18"}}{"week":{"id":"246","start":"05\/04\/18","end":"12\/04\/18"}}
But this form is wrong as it is multiple JSON's I would need to add [] and ',' How could I do this to stay like this:
[{"week":{"id":"247","start":"12\/04\/18","end":"19\/04\/18"}},{"week":{"id":"246","start":"05\/04\/18","end":"12\/04\/18"}}]
Upvotes: 0
Views: 129
Reputation: 1106
By observing your output:
{"week":{"id":"247","start":"12\/04\/18","end":"19\/04\/18"}}{"week":{"id":"246","start":"05\/04\/18","end":"12\/04\/18"}}
Looks like you are iterating the setWeek
function which is doing nothing but echoing json_encoded
array many times in the iteration so the output is like this.
What you can do is return array in setWeek()
and push that in a new a new array and then json_encode that new array like this:
$newArray = [];
loopStart: // just a placeholder from assumption made by me
// some code
$newArray[] = $this->setWeek($week);
loopEnd;
echo json_encode($newArray);
And your setWeek()
:
function setWeek($week) {
preg_match_all("/[\d\/]+/", $week, $output, PREG_SET_ORDER, 0);
$this->week = array("week" =>
array('id' => $output[0][0], "start" => $output[1][0], "end" => $output[2][0]));
$json = json_encode($this->week);
return $this->week;
}
This should solve your problem.
P.S. This code also needs many refactors because this breaks many fundamental rules. Also my assumptions may be wrong if I am wrong please update your questions so that the question will be much clear.
Upvotes: 1
Reputation: 1833
Change:
$this->week = array("week" =>
array('id' => $output[0][0], "start" => $output[1][0], "end" => $output[2][0]));
To
$this->week = array(array("week" =>
array('id' => $output[0][0], "start" => $output[1][0], "end" => $output[2][0])));
Upvotes: 0
Reputation: 734
You need to make $this->week
into an array.
The easiest way to do this would be to change your json_encode
line to
$json = json_encode(array($this->week));
That said, there's a lot of refactoring to be done with this code that's outside of the scope of this question.
Upvotes: 1