I have an array in php as given below:-
Array
(
[0] => Array
(
[team1_score] => 10
[team2_score] => 5
[round_number] => 1
[teamtitle1] => Chennai super kings
[teamtitle2] => Spartans
)
[1] => Array
(
[team1_score] => 15
[team2_score] => 10
[round_number] => 1
[teamtitle1] => Lions11
[teamtitle2] => Kings Xl Punjab
)
[2] => Array
(
[team1_score] => 15
[team2_score] => 5
[round_number] => 1
[teamtitle1] => Zimbabwe
[teamtitle2] => Red Steel
)
[3] => Array
(
[team1_score] => 10
[team2_score] => 15
[round_number] => 2
[teamtitle1] => Zimbabwe
[teamtitle2] => Chennai super kings
)
[4] => Array
(
[team1_score] => 15
[team2_score] => 7
[round_number] => 3
[teamtitle1] => Chennai super kings
[teamtitle2] => Chennai super kings
)
)
from this array i want json format array given below:-
[
[ {"name" : "Chennai super kings", "score" : 10 }, {"name" : "spartans", "score" : 5} ],
[ {"name" : "Lions11", "score" : 15 }, {"name" : "Kings Xl Punjab", "score" : 10} ],
[ {"name" : "Zimbabwe", "score" : 15 }, {"name" : "Red Steel", "score" : 5} ],
],
[
[ {"name" : "Chennai super kings", "score" : 10 }, {"name" : "Zimbabwe", "score" : 5} ],
],
[
[ {"name" : "Chennai super kings", "score" : 10 }, {"name" : "Lions11", "score" : 5} ],
]
I've tried this but it is not coming in proper format. Please help me guys i got stuck in this. Any help will be appreciated Thanks in Advance
First you need to modify your data structure so you have separate array for the team1 and team2 combination. Add that to one holding array and then just use json_encode
simple as that.
// $data is your array
$output = [];
foreach ($data as $row) {
$output[] = [
['name'=>$row['teamtitle1'], 'score'=>$row['team1_score']],
['name'=>$row['teamtitle2'], 'score'=>$row['team2_score']]
];
}
echo json_encode($output);
Edit: As stated in the comments if you want to add another record all you have to do is obviously first find the winner and after that add it to the data set like this:
$output[] = ['name'=>'I am the Winner!', 'score'=>'99999'];
json_encode($output);