How to calculate players score with php - php

I have a json string with players statistics and I want to get total player score with that player name here is an example of the json
<code>{
"Players": [
{
"playerId": 1,
"player_name": "Player 1",
"player_score": 10
"game_type": "action"
},
{
"playerId": 2,
"player_name": "Player 1",
"player_score": 120
"game_type": "action"
},
{
"playerId": 1,
"player_name": "Player 1",
"player_score": 233
"game_type": "action"
},
{
"playerId": "n",
"player_name": "Player n",
"player_score": "n"
}
]
}
</code>
In this example I need to find player 1 for example and calculate all points
so this is what it should be right player 1 has 233 points + 10 points = 243 points, $player_name => $totalpoints;
I've trying with loops to do that but with no success.

Try this. By using this you can get the result as you want.
$player_array = json_decode($json_string); // put your json string variable
$palyer_array_total = array();
foreach($player_array as $player){
$palyer_array_total[$player['playerId']]['name'] = $player['player_name'];
if(isset($palyer_array_total[$player['playerId']]['total_score'])){
$palyer_array_total[$player['playerId']]['total_score'] = $palyer_array_total[$player['playerId']]['total_score']+$player['player_score'];
}else{
$palyer_array_total[$player['playerId']]['total_score'] = $player['player_score'];
}
}
echo "<pre>"; print_r($palyer_array_total);

this should work for you! UPDATED
Cheers Mario
$json = '[{"playerId": 1,"player_name": "Player 1","player_score": 10}, {"playerId": 2,"player_name": "Player 1","player_score": 20},{"playerId": 1,"player_name": "Player 1","player_score": 233},{"playerId": "3","player_name": "Player 3","player_score": "3"}]';
$array = json_decode( $json, true );
$totalcount = array();
foreach ($array as $key => $value){
if (!empty($totalcount[$value['playerId']])) {
$totalcount[$value['playerId']] += $value['player_score'];
}
else
{
array_push($totalcount, $value['playerId'],$value['player_score'] );
}
}
foreach ($totalcount as $key => $value) {
echo "Player ".$key." total=".$value."<br>";
}

Loop through the array and then add them.. let me suppose the array name is $players, then..
$total_score = 0;
foreach($players as $key=>$value)
{
if($value['player_name']=='player1')
{
$total_score +=$value['player_score'];
}
}
echo "PLAYER's TOTAL SCORE = ".$total_score;
EDIT:
This looks like JSON code.. so first decode it using json_decode

Here is a way to do it :
//Convert json to php array
$listPlayers = json_decode({
"Players": [
{
"playerId": 1,
"player_name": "Player 1",
"player_score": 10
},
{
"playerId": 2,
"player_name": "Player 1",
"player_score": 120
},
{
"playerId": 1,
"player_name": "Player 1",
"player_score": 233
},
{
"playerId": "n",
"player_name": "Player n",
"player_score": "n"
}
]
});
//Sum score for each player id
$totalByPlayers = array();
foreach($listPlayers as $player)
{
//If player doesnt exists yet, we create it
if(false === isset($totalByPlayers[$player['playerId']]))
{
$totalByPlayers[$player['playerId']] = 0;
}
$totalByPlayers[$player['playerId']] += $player['player_score'];
}
//Then for score of player one :
echo $totalByPlayers[1];

Related

order json array for equal values

hello i have json file which contain like this data
{
"data": [
{
"SN": "210477",
"name": "jane",
"stdcode": "446515",
"total": 611
},
{
"SN": "210474",
"name": "JOHN doe",
"stdcode": "446512",
"total": 610
},
{
"SN": "210475",
"name": "smith doe",
"stdcode": "446513",
"total": 610
},
{
"SN": "210476",
"name": "omar",
"stdcode": "446514",
"total": 610
}
]
}
as you can see there is duplicate in total in the last three data in total which is 610
i want to order this data according to "total" so it be printed like this
1.jane
2.JOHN doe
2.smith doe
2.omar
i have this code that order it but this not what i want
<?php
$get_records = #file_get_contents('./result.json',true);
$decode_records = json_decode($get_records);
$data = $decode_records->data;
usort($data, function($a, $b) {
return $a->total > $b->total ? -1 : 1;
});
for($x=0;$x<=count($data);$x++){
echo $x+1 .".".$data[$x]->name;
}
?>
the code output
1.jane
2.JOHN doe
3.smith doe
4.omar
Check whether the total has changed, and don't increment the rank if not.
$rank = 0;
$last_total = null;
foreach ($data as $d) {
if ($d->total !== $last_total) {
$rank++;
$last_total = $d->total;
}
echo "$rank. {$data->name}<br>";
}
Note that this means that the next index after all the duplicates will be ranked #3. If you want it to jump to 5 you need to use the array index as well.
$last_total = null;
foreach ($data as $i => $d) {
if ($d->total !== $last_rank) {
$rank = $i+1;
$last_total = $d->total;
}
echo "$rank. {$data->name}<br>";
}

how to search inside two JSON files at a time in PHP

I have two JSON files of same format, forexample
1st JSON File
{
"data": {
"business": {
"id": "3NzA0ZDli",
"customers": {
"pageInfo": {
"currentPage": 1,
"totalPages": 695,
"totalCount": 1389
},
"edges": [
{
"node": {
"id": "QnVzaW5lc3M6Z",
"name": "Joe Biden",
"email": "joe#mail.com"
}
},
{
"node": {
"id": "QnVzaW5lc3M6Z",
"name": "MULTIMEDIA PLUMBUM",
"email": "mdi#mail.com"
}
}
]
}
}
}
}
2nd JSON file
{
"data": {
"business": {
"id": "3NzA0ZDli",
"customers": {
"pageInfo": {
"currentPage": 2,
"totalPages": 695,
"totalCount": 1389
},
"edges": [
{
"node": {
"id": "QnVzaW7dQ8N",
"name": "Mark",
"email": "mark#mail.com"
}
},
{
"node": {
"id": "QnVzaW5l5Gy9",
"name": "Trump",
"email": "trump#mail.com"
}
}
]
}
}
}
}
Each user has a unique "id", I want to get their id by searching their name in php, how can I do this
This is my PHP script
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
foreach ($result2 as $k => $v) {
if ($v['data']['business']['edges']['customers']['node']['name'] == "Trump") break;
}
echo $result[$k]['data']['business']['edges']['customers']['node']['name']; //I want to get id for trump "QnVzaW5l5Gy9"
Each user has a unique "id", I want to get their id by searching their name in php. How can I get id by searching name in both files at a time?
Thanks
Since you are looping through json file it will search inside of "data" so you can't use $v['data']
Also since edges is also array that have same values and you want to search inside of it you must make loop on that also
Here is example
foreach ($result2 as $k => $v) {
foreach ($v['business']['customers']['edges'] as $val) {
if ($val['node']['name'] == 'Trump') {
echo '<pre>';
// and now you can access any of those values, echo $val['node']['id'];
print_r($val['node']);
echo '</pre>';
}
}
}
Output
Array
(
[id] => QnVzaW5l5Gy9
[name] => Trump
[email] => trump#mail.com
)
EDIT
Since you want to search in both files at a same time you can put them into array and then use it like this
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
$joined_result = array($result1, $result2);
foreach($joined_result as $val) {
// this will take all nodes where you will search
$node = $val['data']['business']['customers']['edges'];
foreach ($node as $value) {
if ($value['node']['name'] == 'Trump') {
echo '<pre>';
print_r($value['node']);
echo '</pre>';
}
}
}
You have two questions there, no?
The first question I get is "How to get the ID for a certain name"
$node = $result2['data']['business']['customers']['edges']['node'];
if ($node['name'] == "Trump") echo $node['id'];
Almost your code, but I echo the ID when the name matches "Trump".
The second question I see is "How do search both json data at once"
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
$all_data = [$result1, $result2];
foreach($all_data as $data) {
$node = $data['data']['business']['customers']['edges']['node'];
if ($node['name'] == "Trump") echo $node['id'];
}
Transforming both json data to be in an array and then simply looping over the whole array should do the trick.

create tree view like json from existing combined array

I have one combined array of order and its items combined into one array but i am trying to create json structure like order then its items list like wise.
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Output should be like
[
"0":[
{
"OrderNo": "1",
"partycode": "10",
"OrderDetails": [
{
"Item": "abc",
"price": 250
},
{
"Item": "xyz",
"price": 250
}
]
}
],
"1":[
{
"OrderNo": "2",
"partycode": "20",
"OrderDetails": [
{
"Item": "pqr",
"price": 250
},
{
"Item": "lmn",
"price": 250
}
]
}
]
]
This is What i Tried
$mainarray = array();
$orderarray = array();
$orderitemarray = array();
if (count(combinedarray) > 0) {
foreach (combinedarray as $obj) {
$orderarray[] = array("orderid" => $obj->orderid);
$orderitemarray[] = array("Item" => $obj->Item, "price" => $obj->price);
}
}
$mainarray[] = array_unique($orderarray);
$mainarray['OrderDetails'] = $orderitemarray;
echo json_encode($mainarray);
$mainarray = array();
foreach ($combinedarray as $x) {
$id = $x['orderid'];
unset($x['orderid']);
if (! isset($mainarray[$id])) {
$mainarray[$id]['OrderNo'] = $id;
}
$mainarray[$id]["OrderDetails"][] = $x;
}
// Now $mainarray has indexes equal to OrderNo. To count it from zero, use array_values
echo json_encode(array_values($mainarray), JSON_PRETTY_PRINT);
demo
By your given array
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Here is my solution for this
$new = array();
foreach($combinedarray as $r){
$new[$r['orderid']]['orderid'] = $r['orderid'];
$new[$r['orderid']]['partycode'] = $r['partycode'];
$new[$r['orderid']][] = array("item"=>$r['item'],"price"=>$r['price']);
}
$json = json_encode($new);
echo '<pre>';print_r($new);
echo $json;

Store object into array and group all array with the same value in PHP

I'm working on array right now and I need to arrange this based on value.
{
"data": {
"id": 2,
"title": "second evaluation form",
"emp_position": "System Architecture",
"rating": 5,
"segments": [
{
"segment_name": "Job Role ",
"question": "How old are you?"
},
{
"segment_name": "360 Segments",
"question": "What is your food?"
},
{
"segment_name": "360 Segments",
"question": "sample question"
},
]
}
}
What I need to do is to store this object into array and group all question based on segment_name like this:
{
"data":[
{
"id": 2,
"title": "second evaluation form",
"emp_position": "System Architecture",
"rating": 5,
"segments": [
{
"segment_name": "Job Role "
"question_collection": [
{
"id": 4,
"question": "How old are you?"
}
]
},
{
"segment_name": "360 Segments",
"question_collection":[
{
"id": 1,
"question": "What is your food?"
},
{
"id": 2,
"question": "sample question"
}
]
},
]
}
]
}
And this is what I've tried to do:
$array_value =[];
foreach ($query AS $key => &$data) {
$array_value['id'] = $data['id'];
$array_value['title'] = $data['title'];
$array_value['emp_position'] = $data['position'];
$array_value['rating'] = $data['rating_count'];
if ( is_array($data) ) {
$array_value['segments'][$key]['segment_name'] = $data['segment'];
$array_value['segments'][$key]['question'] = $data['question'];
}
}
Collection function might help you find your solution.
$json = '{"data":{"id":2,"title":"second evaluation form","emp_position":"System Architecture","rating":5,"segments":[{"segment_name":"Job Role ","question":"How old are you?"},{"segment_name":"360 Segments","question":"What is your food?"},{"segment_name":"360 Segments","question":"sample question"}]}}';
$array = json_decode($json, true);
$coll = collect($array['data']['segments']);
$coll = $coll->groupBy('segment_name');
dump($coll);
Hope this helps you.Let me know if any problem
Do it like below:-
<?php
$json = '{
"data": {
"id": 2,
"title": "second evaluation form",
"emp_position": "System Architecture",
"rating": 5,
"segments": [
{
"segment_name": "Job Role ",
"id": 4,
"question": "How old are you?"
},
{
"segment_name": "360 Segments",
"id": 1,
"question": "What is your food?"
},
{
"segment_name": "360 Segments",
"id": 2,
"question": "sample question"
}
]
}
}
';
$query = json_decode($json,true);
$segment_array = [];
foreach($query['data']['segments'] as $arr){
$segment_array[$arr['segment_name']]['segment_name'] = $arr['segment_name'];
$segment_array[$arr['segment_name']]['question_collection'][] = ['id'=>$arr['id'],'question'=>$arr['question']] ;
}
$query['data']['segments'] = array_values($segment_array);
echo json_encode($query,JSON_PRETTY_PRINT);
OUTPUT:- https://eval.in/902194
Try this solution, You can loop by array and group all keys
$json = '{
"data": {
"id": 2,
"title": "second evaluation form",
"emp_position": "System Architecture",
"rating": 5,
"segments": [
{
"segment_name": "Job Role ",
"question": "How old are you?"
},
{
"segment_name": "360 Segments",
"question": "What is your food?"
},
{
"segment_name": "360 Segments",
"question": "sample question"
}
]
}
}';
$data = json_decode($json,true);
$segments = $data['data']['segments'];
$new_segemnts = array();
foreach($segments as $segemnt)
{
$key = $segemnt['segment_name'];
$new_segemnts[$key]['segment_name']=$segemnt['segment_name'];
$new_segemnts[$key]['question_collection'][]=array("question"=>$segemnt['question']);
}
$data['data']['segments'] = array_values($new_segemnts);
echo json_encode($data,JSON_PRETTY_PRINT);
DEMO
Here try my answer. I've just editted your existing code so you won't confuse that much. Nothing much to explain here. I included some explaination in my comment.
CODE
$array_value =[];
foreach ($query AS $key => &$data) {
$array_value['id'] = $data['id'];
$array_value['title'] = $data['title'];
$array_value['emp_position'] = $data['position'];
$array_value['rating'] = $data['rating_count'];
if ( is_array($data) ) {
// Check if segment is already added
$has_segment = false;
$segment_key = null;
foreach($array_value['segments'] as $key2 => $val){
//If segment is already added get the key
if($val['segment_name'] == $data['segment']){
$segment_key = $key2;
$has_segment = true;
break;
}
}
// if segment does not exists. create a new array for new segment
if(!$has_segment){
$array_value['segments'] = array();
}
// If new segment, get the index
$segment_key = count($array_value['segments']) - 1;
// If new segment, create segment and question collection array
if(!array_key_exists('question_collection', $array_value['segments'][$segment_key])){
$array_value['segments'][$segment_key]['segment_name'] = $data['segment'];
$array_value['segments'][$segment_key]['question_collection'] = array();
}
//Add the id for question collectiona rray
$array_value['segments'][$segment_key]['question_collection'][] = array(
"id" => $data['question_id'],
"question" => $data['question']
);
}
}

Group SQL data by JSON arrays

I am working on a page for teachers that shows results of students' performance on a test.
To display a graph I want to use Highcharts JavaScript library.
So far I have a PHP script using PDO to create JSON data that later can be fed to Highcharts from a different page.
My problem:
How do I group all data from the same student in an array? See the last example for what I wish to achieve. Also: I wish to enclose all data in an overarching JSON array.
I want this:
[{
"student": "Andreas",
"level" : [4, 3]
}, {
"student": "Eivind",
"level" : [4, 5]
}, {
"student": "Ole",
"level" : [4, 3]
}]
This is what my PHP looks like:
<?php
require("config.inc.php");
$school = $_GET["school"];
$class = $_GET["class"];
//initial query
$query = 'SELECT student, taskid, level FROM task
WHERE school=' . '"' . $school . '"' . ' AND class=' . '"' . $class . '" ORDER BY student';
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["student"] = $row["student"];
$post["level"] = $row["level"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response, JSON_NUMERIC_CHECK);
} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
?>
This is what I get from the PHP:
{
"posts": [
{
"student": "Andreas",
"level": 4
},
{
"student": "Andreas",
"level": 3
},
{
"student": "Eivind",
"level": 4
},
{
"student": "Eivind",
"level": 5
},
{
"student": "Ole",
"level": 4
},
{
"student": "Ole",
"level": 3
}
]
}
var data=[
{ "category" : "Search Engines", "hits" : 5, "bytes" : 50189 },
{ "category" : "Content Server", "hits" : 1, "bytes" : 17308 },
{ "category" : "Content Server", "hits" : 1, "bytes" : 47412 },
{ "category" : "Search Engines", "hits" : 1, "bytes" : 7601 },
{ "category" : "Business", "hits" : 1, "bytes" : 2847 },
{ "category" : "Content Server", "hits" : 1, "bytes" : 24210 },
{ "category" : "Internet Services", "hits" : 1, "bytes" : 3690 },
{ "category" : "Search Engines", "hits" : 6, "bytes" : 613036 },
{ "category" : "Search Engines", "hits" : 1, "bytes" : 2858 }
];
var res = alasql('SELECT category, sum(hits) AS hits, sum(bytes) as bytes \
FROM ? \
GROUP BY category \
ORDER BY bytes DESC',[data]);
You will get output as:
[{"category":"Search Engines","hits":13,"bytes":673684},
{"category":"Content Server","hits":3,"bytes":88930},
{"category":"Internet Services","hits":1,"bytes":3690},
{"category":"Business","hits":1,"bytes":2847}]
You can construct an array like this pretty easily by using the student names as array keys. After you have built the array, you can use array_values to convert the string keys back to numeric keys.
...
if ($rows) {
foreach ($rows as $row) {
$posts[$row['student']]['student'] = $row['student'];
$posts[$row['student']]['level'][] = $row['level'];
}
$response = array_values($posts);
echo json_encode($response, JSON_NUMERIC_CHECK);
} else { ...
This should give you the following $response:
[
{
"student": "Andreas",
"level": [4, 3]
},
{
"student": "Eivind",
"level": [4, 5]
},
{
"student": "Ole",
"level": [4, 3]
}
]
In php you can do this:
In your foreach
foreach ($rows as $row) {
$post = array();
$post["student"] = $row["student"];
$post["level"] = $row["level"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
you need to do something like this:
<?php
$response = array();
$response["posts"] = array();
$students = array("student1", "student2", "student3", "student1");
$tempArray = array();
foreach ($students as $student) {
$lvl = 1;
if(!isset($tempArray[$student])){
$tempArray[$student] = array("name" => $student, "level" => array($lvl));
}
else{
$tempArray[$student]["level"][] = $lvl;
}
}
// add it to the array
$response["posts"] = $tempArray;
// encode array
$response = json_encode($response);
echo "<br><br><br> ";
// example
// decode and make it a array for easier looping.
$response = (array)json_decode($response);
$responsePosts = (array) $response["posts"];
// foreach post
foreach($response["posts"] as $keyP => $valueP){
// convert to array same as above
$valueP = (array) $valueP;
// key that is kinda useless but made it the student name so i can easily see if it already exists
echo "key :".$keyP." <br />";
// name of the student
echo "name :".$valueP["name"]." <br />";
// all the levels
echo "levels: ";
foreach($valueP["level"] as $lvl){
echo $lvl." ";
}
echo "<br /><br />";
}
?>
This should work. Atm i use the student name as a key to see if it already exists otherwise you need to loop through all the arrays and do a "name" === $student most likely.
No push is required.

Categories