Sorting arrays in Laravel following a specific parametre - php

I have a variable which is an array of arrays
$janvier[]=array( 'type', 'date');
I want to sort it following the date so I used this code
$janvier=> $janvier->sortby($janvier['date'])
but it shows me this error:
call to a member function sortby() on array
Couldn't find what's wrong
I'm so used to low level languages this is my first time using a high level language

You can create a custom function for this case:
array_sort_by_column($array, 'date');
function array_sort_by_column(&$array, $column, $direction = SORT_ASC) {
$reference_array = array();
foreach($array as $key => $row) {
$reference_array[$key] = $row[$column];
}
array_multisort($reference_array, $direction, $array);
}
For more you can check this question

sortBy is a collection method from laravel, you can't use it on a array.
If you want to sort the array by the key data use this code:
$janvier = array_multisort(array_values($janvier), SORT_DESC, array_keys($janvier), SORT_ASC, $janvier);
Look at the array_multisort method for more info

Related

Laravel collection find common items

I am trying to find the common items existing in a collection like the following one:
I would like to end up with a new collection that contains the 928 and the 895 (common items between the key 95 and the key 94).
How can I do it?
I have an array of keys, but I don't understand how to loop over the keys AND the values without create a mess of variables and additional arrays:
foreach ($ids as $id) {
$item_ids->each(function ($item, $key) {
});
}
Well, I ended up with that solution:
$all = $item_ids->all();
$list = [];
foreach ($all as $single) {
$list[] = $single->toArray();
}
$commonItems = collect(call_user_func_array('array_intersect', $list));
So, this is a more laravel approach:
$items = $item_ids['items']->map(function ($item){
$collection[] = $item['items'];
return collect($collection)->duplicates();
});

Laravel collection for loops and mappings

I am trying to refactor my code, and remove a for loop.
$result = [];
foreach ($data as $language) {
$result[$language->{$key}] = $language->{$column};
}
This became:
$result = $data->map(function($language) use ($key, $column){
return [$language->{$key} => $language->{$column}];
});
But now instead of:
[
"key":"value",
"key":"value"
]
I am getting
[
{
"key":"value"
},
{
"key":"value"
}
]
Why doesn't it map like an array?
Please refer this URL
For Example:
$emailLookup = $employees->reduce(function ($emailLookup, $employee) {
$emailLookup[$employee['email']] = $employee['name'];
return $emailLookup;
}, []);
Gives you result like:
const emailLookup = {
'john#example.com': 'John',
'jane#example.com': 'Jane',
'dave#example.com': 'Dave',
};
In your case do like:
$result = $data->reduce(function($language, $a){
$language[$a['any_you_want']] = $a['any_you_want'];
return $language;
}, []);
Hope this helps you!
You probably needed to mapWithKeys:
$result = $data->mapWithKeys(function($language) use ($key, $column){
return [$language->{$key} => $language->{$column}];
});
The method has been available since Laravel 5.3
According to the docs:
The mapWithKeys method iterates through the collection and passes each value to the given callback. The callback should return an associative array containing a single key / value pair:
For your simple use case, pluck() is the method you're looking for. It will build a new collection using one column of an existing array. You can also pass in a second field that will be used to key the new collection.
So, in your case, the data column you're selecting is $column, and the column to use as the key for the new collection is $key. Your code would be:
$result = $data->pluck($column, $key);
This says "give me a collection of all of the $column data, and key it by the $key data".
If you want the plain array instead of the collection, just call all() on the result:
$result = $data->pluck($column, $key)->all();
If you need to "pluck" more than one column of data, you will need to use the mapWithKeys() method already mentioned.
Here in loop you need to use as key value pair
$result = [];
foreach ($data as $key => $language) {
$result[$key] = $language;
}

php help - sort multidimensional array buy using another array

I hope somebody can help me, I need to order array No.1 based on the position of array no.2 , using the array1->id to array2->products_id
Array No.1
{"products":[{"id": 9847760515,"title":"Some Dress"},{"id": 10769647619,"title":"Shirt"}]}
Array No.2 where the order is: (position":x)
{"collects":[{"id":38447047939,"product_id":10769647619,"position":1,"sort_value":"0000000001"},{"id":25425594499,"product_id":9847760515,"position":3,"sort_value":"0000000003"}]}
foreach ($sorted_array as $product) {
echo $product['name'];
}
Appreciate any help
You can create a function which will take both arrays and order them by whatever format you need it to be in:
/**
* sort_array will take two arrays and will sort the first based on the second
*
* #param $array the array you want to reorder
* #param $order the array with the pattern
*
* #return array_multisort with reordered array
*/
function sort_array(&$array, $order, $dir = SORT_ASC) {
// create an empty array here
$sort = array();
// loop through the main array
foreach ($array as $key => $row) {
$sort[$key] = $row[$order];
}
array_multisort($sort, $dir, $array);
}
Using array_multisort you can "sort multiple or multi-dimensional arrays." For more information on that you can read it on PHP Manual; with further information on how it can be used.
I based this answer with previously answered question on Stack Overflow.
You can use usort function supplying it with order from the second array:
$sort = array_combine(
array_column($array2, 'product_id'),
array_column($array2, 'position')
);
usort($array1, function ($a, $b) use ($sort) {
return $sort[$a['id']] - $sort[$b['id']];
});
We prepare sorting dictionary ($sort) by using array_combine and array_column functions. Pay attention, that in order to use array_column function you have to convert your JSON to an array of arrays (pass true as the second argument of json_decode function).
Here is working demo.

PHP sort array through personalized order

I need to sort an array, I've done this before but it has been easy because the array had numbers or letters to sort in ascedning/descending or alphabetical order.. In this case i have an array of which each element has 3 values, eg:
array[0]=code=1234
=description='example array'
=orderCode=P
array[1]=code=1235
=description='example array1'
=orderCode=A
.
.
.
Now i need to order theese reading the orderCode value in this order: P,I,B,C,A,S,D.
The way i thought of getting arround it was to add another value to the array and to something like:
if($array[$c]['orderCode'] == 'P')
$array[$c]['newOrderCode'] = 0;
if($array[$c]['orderCode'] == 'I')
$array[$c]['newOrderCode'] = 1;
if($array[$c]['orderCode'] == 'B')
$array[$c]['newOrderCode'] = 2;
or a switch case and then order it by the new value. This would work, but my question is, is there a function I can pass the array to and an orderring string or something?
Thank you,
James
In php 5.3 and above you can use usort with a closure.
$order = array('P','I','B','C','A','S','D');
usort($array, function ($a, $b) use ($order){
return array_search($a["orderCode"], $order) - array_search($b["orderCode"], $order);
});
prior to that you have to create a sorter function
function orderCode_sorter($a, $b){
$order = array('P','I','B','C','A','S','D');
return array_search($a["orderCode"], $order) - array_search($b["orderCode"], $order);
}
usort($array, "orderCode_sorter");
use function user defined and choise sort by key or value you need see all list function here: http://www.php.net/manual/en/array.sorting.php

array_multisort with multi-dimensional object array

I want to sort a multi-dimensional array in which each array is an object. The example at
http://php.net/manual/en/function.array-multisort.php
indicates the need to create an array of the columns on which to sort
foreach ($data as $key => $row) {
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
}
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
but I get the followiwng error if I format my request in this format:
Catchable fatal error: Object of class stdClass could not be converted to string
Code is as follows with a key/value pair for last name with key last_name:
foreach ($mw_users as $key => $value) {
$last_name[$key] = $row['last_name'];
}
array_multisort($last_name, SORT_ASC, $mw_users);
Define an array for each column you wish to sort by and add the column values using the object reference syntax:
// Obtain a list of columns
foreach ($mw_users as $mw_user) {
$lastnames[] = $mw_user->last_name;
$firstnames[] = $mw_user->first_name;
}
// Sort the data with volume descending, edition ascending
// Add $mw_users as the last parameter, to sort by the common key
array_multisort($lastnames, SORT_ASC, $firstnames, SORT_ASC, $mw_users);
It's similar to sorting database results: http://php.net/...array-multisort.php....
When sorting arrays of objects in PHP, it helps to override __tostring() magic method. That way the various sort methods perceive the object as something comparable. For example, a staff object could output the name, or staff id of that staff member.

Categories