php help - sort multidimensional array buy using another array - php

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.

Related

Sort foreach loop result

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.

Sorting arrays in Laravel following a specific parametre

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

PHP, foreach doesnt return an array but array_map with same code returns an array

I want the foreach to return arrays but it just returns a single array. But the array_map with same code does.
What is the correct way of getting the arrays out of the foreach.
Why does foreach behaves differently than array_map.
Inside the file (userdata.php)
Reme:Reme1991#jourrapide.com
george bush:GeorgeBush#gmail.com
obama:obama#gmail.com
Using array_map
function registered_users(){
$file_user = file('userdata.php');
return array_map(function($user){
return explode(':',$user);
},$file_user);
} //returns the exploded array correctly.
Using foreach
function registered_users(){
$file_user = file('userdata.php');
foreach ($file_user as $user) {
return explode(':',$user);
}
}// returns Array ( [0] => Reme [1] => Reme1991#jourrapide.com )
Because array_map() iterates over all elements in the array.... the foreach() would do the same except that your return is jumping out of it on the first iteration.
function registered_users(){
$users = [];
$file_user = file('userdata.php');
foreach ($file_user as $user) {
$users[] = explode(':',$user);
}
return $users;
}
EDIT
In response to your question "Why doesn't a return from array_map terminate the iteration?"
Because array_map() is a function that loops/iterates every element in the array, executing a "callback" function against each element. Your return is in the "callback" function, which acts on one individual array element at a time, and is called multiple times by array_map(), once for each element of the array in turn.
The return in your "callback" is simply returning a modified value for that one individual element (the current element in the array_map() loop) to the array_map() function.... it's telling array_map() what the new element value should be.
The array_map() function itself can't be interrupted: it will then continue iterating over the next element, sending that in turn to the "callback" function until it has done so for every element in the array.

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