Laravel Sort by data in JSON - php

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();

Related

modify json data in php laravel

I've a sample json data
{
"cities": {
"total": 100,
"count":5000,
"cities_list" : [{
"name": "city1",
"count": 1000
},
{
"name": "city2",
"count": 2000
}
]
}
}
How can I append the cities_list array directly to cities which would look like
{
"cities": [{
"name": "city1",
"count": 1000
},
{
"name": "city2",
"count": 2000
}
]
}
Not sure, about all the stuff, but i assume your "json" or just associative array is in variable (for example foo)
Now you should set:
$foo["cities"] = $foo["citites"]["citites_list"];
Let's say that your JSON result is stored in a variable called $results
$results = json_decode($results,true); //convert json to array
$modifiedArray= [];
$modifiedArray= $results['cities']['cities_list']->map(function ($item, $key) {
return ['cities'][][
'name' => $item->name,
'count' => $item->count
];
});
This is more of a laravel approach since you also tagged laravel. Your modified array is an array type if you want to be a JSON again you have to encode it into a JSON.
You can use the Unset function
$data= json_decode($your_json);
$json_arr = json_decode($your_json, true);
unset($data->total);
unset($json_arr['total']);

PHP: Convert Object to Associative Array with Object Property as Key

In PHP, I'd like to convert an array of objects like the following to a PHP array, using one of the properties as the associative array keys.
[
{ "id": 2, "name": "Suzy" },
{ "id": 3, "name": "Joe" },
{ "id": 4, "name": "Sara" }
]
like this...
[
2 => "Suzy",
3 => "Joe",
4 => "Sara"
]
I can't use array_map because you can't set the keys from my understanding, but I'm wondering if there's a one-liner way to do it without a foreach loop.
To be clear, I want to maintain the keys in the output array, not puts the original keys inside the new array values like they do here: PHP's array_map including keys
It appears by "object" you mean a JSON object. Given that, you can use array_column() to pull out a single column from each row, and then array_combine() to use one column for the keys and another for the values:
$json = '[
{ "id": 2, "name": "Suzy" },
{ "id": 3, "name": "Joe" },
{ "id": 4, "name": "Sara" }
]';
$array = json_decode($json, true);
$out = array_combine(array_column($array, 'id'), array_column($array, 'name'));
print_r($out);
Yields:
Array
(
[2] => Suzy
[3] => Joe
[4] => Sara
)
2 liners and has a foreach though.
<?php
$json = '[
{ "id": 2, "name": "Suzy" },
{ "id": 3, "name": "Joe" },
{ "id": 4, "name": "Sara" }
]';
$new_array = [];
foreach(json_decode($json,true) as $each_object) $new_array[$each_object['id']] = $each_object['name'];
print_r($new_array);
$json = '[
{ "id": 2, "name": "Suzy" },
{ "id": 3, "name": "Joe" },
{ "id": 4, "name": "Sara" }
]';
$array = json_decode($json, true);
$result = array_column($array, 'name', 'id');

Rewrite json in loop

I have an array, which i wrote like a table for more reability.
[{
"id": "1",
"title": "boune",
"value": "3"
}, {
"id": "2",
"title": "check",
"value": "4"
}, {
"id": "3",
"title": "boune",
"value": "5"
}]
As the result of what i want to see is this json, where 'value' of identical 'titles' united inside [] brackets. I am very newbie in php. I undestand that i need for loop to sort query result, but can`t heck...Cant even put my mind to it...
[{
"id":"1",
"title": "boune",
"value": [3, 5]
}]
<?php
$json = '[{"id":"1","title":"boune","value":"3"},{"id":"2","title":"check","value":"4"},{"id":"3","title":"boune","value":"5"}]';
$json_data = json_decode($json,true);
function accumulateValuesByTitle($json_data){
$hash = [];
foreach($json_data as $each_record){
if(isset($hash[$each_record['title']])){
$hash[$each_record['title']]['value'][] = $each_record['value'];
if($hash[$each_record['title']]['id'] > $each_record['id']){
$hash[$each_record['title']]['id'] = $each_record['id'];
}
}else{
$hash[$each_record['title']] = $each_record;
$hash[$each_record['title']]['value'] = [$hash[$each_record['title']]['value']];
}
}
return array_values($hash);
}
$modified_data = accumulateValuesByTitle($json_data);
echo json_encode($modified_data);

how to sort a json object in laravel

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.

fetch values from array within an array

I have a multidimensional array, i wish to extract each value from this array.
The array is stored in $data.
{"success":true,"categories":
[
{"
category_id":"C1",
"parent_id":"P1",
"name":"N1",
"categories":
[
{
"category_id":"C11",
"parent_id":"P11",
"name":"N11",
},
{
"category_id":"C12",
"parent_id":"P12",
"name":"N12",
},
],
"status":"1"
},
{
category_id":"C2",
"parent_id":"P2",
"name":"N2",
"categories":
[
{
"category_id":"C21",
"parent_id":"P21",
"name":"N21",
[
{
"category_id":"C22",
"parent_id":"P23",
"name":"N24",
}
],
"status":"2"
}
],
"status":"3"
},
]
}
I tried using
$total = $data['categories']['category_id'];
to fetch value C11
but wasn't able to do so.
can anyone tell how i can fetch all the data especially C22
You have to first use json_decode.
$array = json_decode($data, true);
Then you can access the array as you have stated.
Or loop throught the categories:
if (!empty($array)) {
foreach ($array['categories'] as $category) {
echo $category['id'];
}
}
You may have to do this recursively to loop through the categories within the categories. But it depends completely what you want to achieve. A nested loop could do the job if it is always just one level deep.
EDIT
The JSON you have provided is not quite right, I have given a corrected one below:
{
"success": true,
"categories": [
{
"category_id": "C1",
"parent_id": "P1",
"name": "N1",
"categories": [
{
"category_id": "C11",
"parent_id": "P11",
"name": "N11"
},
{
"category_id": "C12",
"parent_id": "P12",
"name": "N12"
}
],
"status": "1"
},
{
"category_id": "C2",
"parent_id": "P2",
"name": "N2",
"categories": [
{
"category_id": "C21",
"parent_id": "P21",
"name": "N21",
"categories": [
{
"category_id": "C22",
"parent_id": "P23",
"name": "N24"
}
],
"status": "2"
}
],
"status": "3"
}
]
}
There were a few trailing commas and missing quote marks.
The data is not in PHP array, its a JSON array. You have to decode it, by using json_decode() function.
That's JSON, not php multidimensional array. You can use json_decode function to read through it.

Categories