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.
Related
I want to sort it by $distance base in foreach loop in my VIEWS.. so heres my code in Models
$db = $this->getDbo();
$query = $db->getQuery(true)
->select('*')
->from('#__load');
$db->setQuery($query);
$db->query();
$rows = $db->loadObjectList();
return $db->loadObjectList();
This is the code in my View where i want to sort it by distance
foreach ($this->items as $i => $item) {
$distance = $item->result1 * $item->result2
sort($distance)
}
echo $distance
result
3, 6, 2, 7, 8
i want to show like this
2, 3, 6, 7, 8
sort works on an array, and what you are doing is you are calling sort on every item in the array which wont work.
What you can do instead is do your foreach loop and then sort after:
$array = [];
foreach ($this->items as $i => $item) {
$distance = $item->result1 * $item->result2;
$array[] = $distance;
}
sort($array);
var_dump($array);
https://www.php.net/manual/en/function.sort.php
First Convert your result $this->items into (array)$this->items and then use one of the following function :
sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to the value
ksort() - sort associative arrays in ascending order, according to the key
arsort() - sort associative arrays in descending order, according to the value
krsort() - sort associative arrays in descending order, according to the key
and get sorted value.
There are a few things here that don't make sense to me, so I'll blindly try to refactor your scripts and put all of the processing in the model where it belongs (you shouldn't be manipulating data in the view).
Untested snippet:
$db = $this->getDbo();
$query = $db->getQuery(true)
->select('result1 * result2')
->from('#__load')
->orderBy(1);
$db->setQuery($query);
return $db->loadColumn();
Relevant pages to read:
How can a query multiply 2 cell for each row MySQL?
what is this order by 1?
https://docs.joomla.org/Selecting_data_using_JDatabase
I expect that your view will now receive the following sorted and indexed array:
$this->items = [2, 3, 6, 7, 8];
If you are a Joomla user, come join us at Joomla Stack Exchange. Have a browse of my answers to mysql tagged questions for explained examples and best practices.
If you are living in Brisvegas, come to our monthly Joomla User Group Meetup in West End (we aren't scary people). This is a place where you can leverage an IRL network of people that want to help you grow your skills and get your projects finished.
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
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.
i have a collection object
$di=array();
$products= $this->customerFactory->create()->getCollection()->addAttributeToSelect('*')->addFieldToFilter('entity_id','22');
foreach ($products as $key => $value)
{ # code... }
I want to know how to loop through this collection and create associative array ..and if result has multiple rows how to loop through it.
As final result i should get the array as
{key=>value, key1=>value1}
First of all, getCollection() already returns an array of elements of the given collection, with all its attributes (addAttributeToSelect('*')), so you are already receiving an array of objects rather than a multi-dimensional array.
In the simplest of all cases and if you need a JSON array containing all the products with all attributes, it would be as simple as this:
$jsonArray= json_encode($products); // converts all elements into a JSON representation
If you would need an associative array of elements rather than an array of objects, typecast the objects:
$assocArray= array();
foreach ($products as $product) {
$assocArray[]= (array) $product; // type-casting to array
}
If you want to iterate over each property of each product (I wouldn't know why you would want that), here's that version:
$assocArray= array();
foreach ($products as $product) {
$rowArray= array();
foreach ($product as $key => $val) {
$rowArray[$key]= $val;
}
$assocArray[]= $rowArray;
}
Hope that gives you an idea of how collections can be used in Magento work.
I have an array of objects with a 'category' property. I need to get a list of the different categories, how can I do this given that I have a method to get the category from the object? Shown below creates a list of all the categories in the array, but obviously has lots of repeated categories:
foreach (getSourceCodes() as $source) {
echo $source->getCategory();
}
You can use array_unique() in php.
$categories = array();
foreach (getSourceCodes() as $source) {
array_push($categories, $source->getCategory());
}
$categories = array_unique($categories);
If categories is multidimensional, then use this method to serialise it, then get unique array and then change it back to array.
$categories = array_map("unserialize", array_unique(array_map("serialize", $categories)));
If you use the category as an array key, it will be unique by definition.
foreach (getSourceCodes() as $source) {
// The value is irrelevant. You can use a counter if you want to keep track of that.
$an_array[$source->getCategory()] = true;
// The key is just overwritten for duplicate values of getCategory()
}
// Then you can use array_keys to get the keys as values.
var_dump(array_keys($an_array));
Not sure what format your list is in but assumed comma separated values...
$aCategories = array();
$aList = array();
foreach (getSourceCodes() as $source) {
// Get categories as comma separated string list???
$sList = $source->getCategory();
// Convert string list to array
$aTmpList = explode(",",$sList);
//Check temp list against current list for new categories
$aDiffList = array_diff($aList,$atmpList);
//Merge new categories into current list
$aList = array_merge($aDiffList,$aList);
}
// Convert array to string list
$sCategories = implode(",", $aList);