order json array for equal values - php

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>";
}

Related

Group PHP array values based on 2 sub-values

I have called a JSON array from an API and used json_decode to assign them to a PHP variable.
The array looks like this:
[
{
"id": "1",
"abbr": "XXX",
"title": "YYY",
"visible_from_lat": "85",
"visible_to_lat": "-75",
},
{
"id": "2",
"abbr": "AAA",
"title": "BBB",
"visible_from_lat": "85",
"visible_to_lat": "-75",
}
]
The array has approx 50 items in total, all of which have a visible_from_lat and a visible_to_lat. What I need to do is group each items like so:
visible_from_lat > 0 then assign to variable1
visible_from_lat < 0 then assign to variable2
Any idea's how I do this?
Here there is a basic solution, assuming that in data.json file there are your json data:
<?php
$array = json_decode(file_get_contents("data.json"));
$resulSetPositive = [];
$resulSetNegative = [];
foreach ($array as $obj) {
if(isset($obj->visible_from_lat)) {
if($obj->visible_from_lat > 0) {
$resulSetPositive[] = $obj; // add obj to positive result set
}
else if($obj->visible_from_lat < 0) {
$resulSetNegative[] = $obj; // add obj to negative result set
}
}
}
file_put_contents("negative.json", json_encode($resulSetNegative, JSON_PRETTY_PRINT));
file_put_contents("positive.json", json_encode($resulSetPositive, JSON_PRETTY_PRINT));

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;

access to properties of an array contain json formatted elements in laravel

suppose I have an Array like this :
$myArray =
[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]
Each element of array has json format. and now I want to get name of element that have id of 87 for example.
Firstly How can I found that is there element with this id then get name property of that?
Decode JSON string into array. Then use Laravel's array_first method.
<?php
$myArray = '[{"id": 86,"name": "admin/login"},{"id": 87,"name": "admin/logout"},{"id": 88,"name": "admin/desktop"}]';
// Decode into array
$array = json_decode($myArray, true);
// Find item with correct id
$result = array_first($array, function($key, $value){
return $value['id'] === 87;
}, false);
if ($result) {
echo 'Item found, it\'s name is: '.$result['name'];
}
If you have id you like to find in variable, you have to use use construct.
// ID to search for
$searchID = 87;
// Find item with correct id
$result = array_first($array, function($key, $value) use($searchID){
return $value['id'] === $searchID;
}, false);
Try using this:
$newArray = json_decode($myArray);
and you'll get type of array
[
[
"id"=> 86,
"name"=> "admin/login"
],.....
........
]
Your $myArray is incorrect so, assuming it is a json string you can do this in the following way :
At first json_decode it into an arry.
Loop through the elements to find out you desired value(87).
Keep a flag which will tell if you have actually found any value.
<?php
$myArray =
'[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]';
$myArray = json_decode($myArray , true);
$found = 0;
foreach($myArray as $anArray)
{
if($anArray['id'] == 87)
{
var_dump($anArray['name']);
$found = 1;
}
}
if($found == 1)
{
var_dump("Element found.");
}
else
{
var_dump("Element not found. ");
}
?>

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.

How to calculate players score with 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];

Categories