i have the following response, how to sort it depending on the distnace
{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "tito",
"distance": 74,
},
{
"id": 67,
"name": "liver pool",
"distance": 83
},
{
"id": 67,
"name": "Text",
"distance": 72
}
]
}
i tried the usort but i didn't make it.
i also tried this answer here but it seems to be different than the one i need
In pure PHP 7
<?php
$json = '{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "tito",
"distance": 74
},
{
"id": 67,
"name": "liver pool",
"distance": 83
},
{
"id": 67,
"name": "Text",
"distance": 72
}
]
}';
$array = json_decode($json, true);
usort($array['InnerData'], function($a, $b) {
return $a['distance'] <=> $b['distance'];
});
print_r($array);
As #hdifen suggested, if you're using Laravel it's a breeze to do this.
$json = '{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "tito",
"distance": 74
},
{
"id": 67,
"name": "liver pool",
"distance": 83
},
{
"id": 67,
"name": "Text",
"distance": 72
}
]
}';
$data = json_decode($json, true);
$data['InnerData'] = collect($data['InnerData'])->sortBy('distance', SORT_REGULAR, true);
$encoded = json_encode($data);
echo $encoded;
Output:
{
"Message":"Done.",
"Status":true,
"InnerData":{
"1":{
"id":67,
"name":"liver pool",
"distance":83
},
"0":{
"id":66,
"name":"tito",
"distance":74
},
"2":{
"id":67,
"name":"Text",
"distance":72
}
}
}
Json is mainly used as a common format for sending data.
In Laravel you can convert a json object to a php array easily by using json_decode().
$phpArray = json_decode($json);
From here you can convert it to a collection to take advantage of laravels collection functions.
$laravelArray = collect($phpArray);
After this take a look at https://laravel.com/docs/5.5/collections to do sort/filter or do whatever you want to the array.
Related
I am creating a json file from my array:
$file = json_encode($array);
The json file will look like this:
[
{
"name": "file1.html",
"date": "2019-01-29T20:33:57.000163Z",
"size": "348"
}
{
"name": "file2.xml",
"date": "2019-01-29T20:33:57.000167Z",
"size": "401"
}
{
"name": "file3.html",
"date": "2019-01-29T20:33:57.000171Z",
"size": "1314"
}
]
But I need to create a json file with some little bit different format. The output I need is:
{
"draw": 1,
"recordsTotal": 5000,
"recordsFiltered": 5000,
"data": [
{
"name": "file1.html",
"date": "2019-01-29T20:33:57.000163Z",
"size": "348"
}
{
"name": "file2.xml",
"date": "2019-01-29T20:33:57.000167Z",
"size": "401"
}
{
"name": "file3.html",
"date": "2019-01-29T20:33:57.000171Z",
"size": "1314"
}
]
}
Is this possible with json_encode?
Create a new array with rest of the info and assign current array data into it as well.
$newArray = array(
'draw'=> 1,
'recordsTotal'=> 5000,
'recordsFiltered'=> 5000,
'data'=>$array
);
$file = json_encode($newArray);
Let's say I have a Model which outputs 3 models that is this data:
[
{
"id": 1,
"data": [
{
"id": "coins",
"qty": 3
},
{
"id": "ruby",
"qty": 52
}
]
},
{
"id": 2,
"data": [
{
"id": "coins",
"qty": 140
}
]
},
{
"id": 3,
"data": [
{
"id": "coins",
"qty": 84
}
]
}
]
How would I, using Collections, sort this data by coins's qty and who has the most.
A nice clean way of doing this is with the "." operator.
$projects = Project::all()->load('tasks')->sortBy('data.qty');
Json is mainly used as a common format for sending data.
In Laravel you can convert a json object to a php array easily by using json_decode().
$phpArray = json_decode($json);
From here you can convert it to a collection to take advantage of laravels collection functions.
$laravelArray = collect($phpArray);
After this take a look at https://laravel.com/docs/5.8/collections to do sort/filter or do whatever you want to the array.
Or you can use pure php to solve this
$json is your json retrieved
$array = json_decode($json, true);
usort($array['data'], function($a, $b) {
return $a['qty'] <=> $b['qty'];
});
print_r($array);
See this example code
<?php
$json = '{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "first",
"distance": 74
},
{
"id": 67,
"name": "second",
"distance": 153
},
{
"id": 68,
"name": "third",
"distance": 172
}
]
}';
$array = json_decode($json, true);
usort($array['InnerData'], function($a, $b) {
return $a['distance'] <=> $b['distance'];
});
print_r($array);
I hope it's helps you.
Thanks.
try this
$array = collect($array)->sortBy('data.qty')->reverse()->toArray();
Well, I have a web project and I have to be saving things temporarily, I started work with a json file, so far I can add and update.
The json file looks like this:
[
{
"username": "Baldwin",
"products": [
{
"id": 0,
"amount": 10
},
{
"id": 1,
"amount": 9
},
{
"id": 2,
"amount": 9
}
]
},
{
"username": "Alice",
"products": [
{
"id": 0,
"amount": 11
},
{
"id": 1,
"amount": 13
},
{
"id": 2,
"amount": 6
}
]
},
{
"username": "Terry",
"products": [
{
"id": 0,
"amount": 12
},
{
"id": 1,
"amount": 14
},
{
"id": 2,
"amount": 5
}
]
}
]
The problem comes when I want to delete an specific array or when I want to delete it completely, I can do it and it works fine, but I have the doubt about why when I delete the object, other fields are add to the json file, like an id.
When i delete just one product inside of the "products" array something like this happen:
[
{
"username": "Baldwin",
"products": { "1": { "id": 1, "amount": 9 }, "2": { "id": 2, "amount": 9 } }
},
{
"username": "Alice",
"products": [
{ "id": 0, "amount": 11 },
{ "id": 1, "amount": 13 },
{ "id": 2, "amount": 6 }
]
},
{
"username": "Terry",
"products": [
{ "id": 0, "amount": 12 },
{ "id": 1, "amount": 14 },
{ "id": 2, "amount": 5 }
]
}
]
And when i delete a complete array from the json file, something like this happen:
{
"1": {
"username": "Alice",
"products": [
{ "id": 0, "amount": 11 },
{ "id": 1, "amount": 13 },
{ "id": 2, "amount": 6 }
]
},
"2": {
"username": "Terry",
"products": [
{ "id": 0, "amount": 12 },
{ "id": 1, "amount": 14 },
{ "id": 2, "amount": 5 }
]
}
}
My php file to delete:
<?php
// load file
$data = file_get_contents('results.json');
// decode json to associative array
$json_arr = json_decode($data, true);
$flag = false;
// We check if the user wants to delete all or just one product
if(isset($_POST["all"])):
$username = $_POST["username"];
foreach ($json_arr as $key => $value):
// find the username on the json file
if($value["username"] == $username):
unset($json_arr[$key]);
break;
endif;
endforeach;
elseif(isset($_POST["one"])):
$username = $_POST["username"];
$id = $_POST["id"];
foreach ($json_arr as $key => $value):
// find the username on the json file
if($value["username"] == $username):
// loop products of the current username
foreach ($json_arr[$key]["products"] as $k => $product):
// find the id of the product
if($json_arr[$key]["products"][$k]["id"] == (int)$id):
// delete the product
unset($json_arr[$key]["products"][$k]);
endif;
endforeach;
endif;
endforeach;
endif;
// encode json and save to file
file_put_contents('results.json', json_encode($json_arr));
// redirect to show.php
header("Location: show.php");
?>
I've been taking a look to questions like this one but i couldn't find something with php, i would like to know how to solve this or if this is normal.
What happens when you use unset($json_arr[0]) is that the first element is removed, but the keys are not updated. If you inspect the array after the removal, you'll find that your array has two elements, at $json_arr[1] and $json_arr[2].
When you then perform a json_encode($json_arr) on this, PHP's JSON decoder looks at the array and since arrays are supposed to begin at the 0th element but this array begins at 1, it decides that in order to preserve the keys, the array would have to be converted to an associative array - which transforms the integer array keys into string keys in JSON.
For a short and quick solution, you can try:
$json_arr = array_diff($json_arr, [$key]);
You could even use array_splice or array_values - see here for inspiration.
I have the php file
<?php
$str = '{
"champions": [{
"id": 24,
"stats": {
"armor": 27.04,
"attackrange": 125.0,
}
}, {
"id": 37,
"stats": {
"armor": 20.544,
"attackrange": 550.0,
}
}],
"matches": [{
"timestamp": 1433644800,
"champion": 427,
"lane": "TOP"
}, {"timestamp": 1453702800,
"champion": 103,
"lane": "MIDDLE"
}]
}';
$array = json_decode($str,true);// read string to array (true means array, false means object)
var_dump($array);
$champions = $array["champions"];
var_dump($champions);
which outputs null for both var_dumps. What is my mistake? Thanks. Is it maybe a problem that there are square brakets in the json snippet?
You have errors in your JSON.
Remove , in the end of [champions][stats] arrays.
please remove comma separation from every last element of champions->stats like below then do decode
{
"champions": [
{
"id": 24,
"stats": {
"armor": 27.04,
"attackrange": 125
}
},
{
"id": 37,
"stats": {
"armor": 20.544,
"attackrange": 550
}
}
],
"matches": [
{
"timestamp": 1433644800,
"champion": 427,
"lane": "TOP"
},
{
"timestamp": 1453702800,
"champion": 103,
"lane": "MIDDLE"
}
]
}
The situation is I have two arrays that is collecting JSON data via the API :
$players = getAPI("http://xx.xxx.xxx.xx:xxxxx/players.json?apiKey=xxxxxxxxxxxxxxxxxxxxxxxx");
$recents = getAPI("xx.xxx.xxx.xx:xxxxx/recent.json?apiKey=xxxxxxxxxxxxxxxxxxxxxxxx");
The method is getting the contents and decoding the JSON into an array.
For the players array we have this data in an array:
$players
[
{
"id": "76561198033377272",
"name": "PitMonk",
"position": {
"x": -339,
"y": 26,
"z": 191
},
"rotation": 128,
"time": 418310,
"ip": "",
"inventory": {
"main": [],
"belt": [
{
"name": "rock",
"amount": 1,
"blueprint": false,
"condition": 100
},
{
"name": "torch",
"amount": 1,
"blueprint": false,
"condition": 100
}
],
"wear": []
}
},
{
"id": "76561198088638439",
"name": "Pippa",
"position": {
"x": -337,
"y": 25,
"z": 177
},
"rotation": 73,
"time": 419136,
"ip": "",
"inventory": {
"main": [
{
"name": "arrow.wooden",
"amount": 12,
"blueprint": false
},
{
"name": "bow.hunting",
"amount": 1,
"blueprint": false,
"condition": 93
},
{
"name": "blueprint_fragment",
"amount": 25,
"blueprint": false
},
{
"name": "metal.fragments",
"amount": 1366,
"blueprint": false
},
{
"name": "metal.refined",
"amount": 48,
"blueprint": false
},
{
"name": "charcoal",
"amount": 1120,
"blueprint": false
},
{
"name": "lowgradefuel",
"amount": 738,
"blueprint": false
}
],
"belt": [
{
"name": "rock",
"amount": 1,
"blueprint": false,
"condition": 100
},
{
"name": "torch",
"amount": 1,
"blueprint": false,
"condition": 100
},
{
"name": "pickaxe",
"amount": 1,
"blueprint": false,
"condition": 76
},
{
"name": "pickaxe",
"amount": 1,
"blueprint": false,
"condition": 17
},
{
"name": "pickaxe",
"amount": 1,
"blueprint": false,
"condition": 100
},
{
"name": "pickaxe",
"amount": 1,
"blueprint": false,
"condition": 100
}
],
"wear": [
{
"name": "burlap.shirt",
"amount": 1,
"blueprint": false
},
{
"name": "attire.hide.skirt",
"amount": 1,
"blueprint": false
}
]
}
}
]
$recents
[
{
"id": "76561198039206786",
"name": "JakeGroves"
},
{
"id": "76561198088638439",
"name": "Pippa"
},
{
"id": "76561198033377272",
"name": "PitMonk"
},
{
"id": "76561198146864439",
"name": "YepWellDone"
},
{
"id": "76561198164836207",
"name": "Baz"
},
{
"id": "76561198076406281",
"name": "xwalnutx"
},
{
"id": "76561197985716090",
"name": "Darkflame134"
},
{
"id": "76561198263423842",
"name": "XitaikiznerX"
},
{
"id": "76561198129952244",
"name": "NatanGamer"
},
{
"id": "76561198071842055",
"name": "Baha Bey"
}
]
As you can see the players is the people connected, and recents is the total list of people who have connected recently.
I have attempted this:
foreach ($players as $player) {
echo $players->name;
}
echo "</br></br>";
foreach ($recent as $rec) {
if ($rec->name != $player->name) {
echo $rec->name . "</br>";
}
}
and it produces the result:
PitMonk Pippa
JakeGroves
PitMonk
YepWellDone
Baz
xwalnutx
Darkflame134
XitaikiznerX
NatanGamer
Baha Bey
So it is only ignoring 'pippa', I am not sure if it is possible to interact with two arrays as such for unique values?
You are interested in listing all names out of $users which don't exist in $players or $recents, right?
Assuming you are only interested in the name:
// First, let's get a new array with all names from both arrays (can contain dups)
$pcNames = array_map($players + $recents, function($playerObject) {
return $playerObject->name;
});
// Next, let's remove all dups
$pcNames = array_unique($pcNames);
// === At this point you have an array with all names from `$players` and `$recents` ===
// === You may do something else with those, but I'll now create another array with ===
// === all users not in the players/recents lists. ===
// Now let's also get a list of names of users in the `$users` variable
$userNames = array_map($users, function($playerObject) {
return $playerObject->name;
});
// And finally let's get all names which are not in players or recents
$diffNames = array_diff($userNames, $pcNames);
// Let's output those to see whether it worked
var_dump($diffNames);
Of course there are other ways depending on your use case. We could for example extract the names of all three arrays and then just use array_diff with 3 arguments (but then you don't have the $pcArray side product), or if you actually want to compare IDs but print names, we would have to change all the inline functions to extract ID instead of name and further down reference the users array to get the actual name, etc.