How to sort an array based on a value - php

$arr['a']['studentname'] = "john";
$arr['b']['studentname'] = "stefen";
$arr['c']['studentname'] = "alex";
is it possible to sort using user defined functions:
usort( $arr )
uasort( $arr )
uksort( $arr )
so based on value which i need to pass, the array should be sorted!
expected output:
if the current value then
Array
(
[c] => Array
(
[studentname] => alex
)
[a] => Array
(
[studentname] => john
)
[b] => Array
(
[studentname] => stefen
)
)
if the current value then
Array
(
[b] => Array
(
[studentname] => stefen
)
[a] => Array
(
[studentname] => john
)
[c] => Array
(
[studentname] => alex
)
)
thanks in advance

If I understood the question, you can use a simple string compare callback:
$arr['a']['studentname'] = "john";
$arr['b']['studentname'] = "stefen";
$arr['c']['studentname'] = "alex";
// A-Z
uasort($arr, function($a, $b) {
return strcmp($a['studentname'], $b['studentname']);
});
print_r($arr);
// Z-A
uasort($arr, function($a, $b) {
return strcmp($b['studentname'], $a['studentname']);
});
print_r($arr);

Try this:
For PHP version > 5.3:
$arr['a']['studentname'] = "john";
$arr['b']['studentname'] = "stefen";
$arr['c']['studentname'] = "alex";
uasort($arr, function($a, $b) {
return strcmp($a['studentname'], $b['studentname']);
});
For PHP version < 5.3:
$arr['a']['studentname'] = "john";
$arr['b']['studentname'] = "stefen";
$arr['c']['studentname'] = "alex";
function sort_by($a, $b) {
return strcmp($a['studentname'], $b['studentname']);
}
uasort($arr, 'sort_by');

Related

Change list to list of associative arrays in PHP

I have list of unique elements and want to change it to list of associative arrays. What is the most elegant way to do this? I tried foreach but it looks bogus.
Expected Input:
array('2019-10-01', '2019-10-02', '2019-10-03')
Expected Output:
array(array('day' => '2019-10-01'), array('day' => '2019-10-02'), array('day' => '2019-10-03'))
You can use array_map:
$array = array('2019-10-01', '2019-10-02', '2019-10-03');
$output = array_map(function ($v) { return array('day' => $v); }, $array);
or a simple foreach:
$output = array();
foreach ($array as $v) {
$output[] = array('day' => $v);
}
In both cases the output is the same:
Array
(
[0] => Array
(
[day] => 2019-10-01
)
[1] => Array
(
[day] => 2019-10-02
)
[2] => Array
(
[day] => 2019-10-03
)
)
Demo on 3v4l.org
See this short code example. it iterates over the given array and associates a key with an increment:
$a = Array('2019-10-01', '2019-10-02', '2019-10-03');
$b = [];
for($x = 0; $x < count($a); $x++) {
$b['day' . $x] = $a[$x];
}
print_r($b);
// output: Array ( [day0] => 2019-10-01 [day1] => 2019-10-02 [day2] => 2019-10-03 )

PHP transform an array with a simple function

Would there be a simple native PHP function that would transform this array:
Array
(
[0] => stdClass Object
(
[id] => 1
[module_libelle] => Qualités esthétiques
)
[1] => stdClass Object
(
[id] => 2
[module_libelle] => Qualités pragmatiques
)
...
)
in this array:
Array
(
[1] => Qualités esthétiques
[2] => Qualités pragmatiques
...
)
without function like foreach?
You can use array_map
$arr = //your array
$result = array_map(function($o){
return $o->module_libelle; //Return the property of the object
}, $arr);
echo "<pre>";
print_r( $result );
echo "</pre>";
This will return as:
Array
(
[0] => Qualités esthétiques
[1] => Qualités pragmatiques
)
Doc: array_map()
If you also want to keep the id as the array key in the result array, you might use array_walk
$result = array();
array_walk($array, function ($value) use (&$result) {
$result[$value->id] = $value->module_libelle;
});
print_r($result);
Demo
Or you might use array_reduce:
$array = array_reduce($array, function($carry, $item) {
$carry[$item->id] = $item->module_libelle;
return $carry;
});
print_r($array);
Demo

PHP Sort Mega-Array by Value

I am looking for some advices how could I sort this kind of Array by 'variant_name' key.
Because Array is really huge I minified it to the looking result state.
...
$filter[2413][1][81][sub_id] = 1;
$filter[2413][1][81][variant_id] = 81;
$filter[2413][1][81][variant_name] = 'Banana';
$filter[2413][2][87][sub_id] = 2;
$filter[2413][2][87][variant_id] = 87;
$filter[2413][2][87][variant_name] = 'Apple';
$filter[2413][3][32][sub_id] = 3;
$filter[2413][3][32][variant_id] = 32;
$filter[2413][3][32][variant_name] = 'Carrot';
...
Keys $filter[x][x][x] are not sequential.
I have tried the sort function I used before but it doesn't work with this kind of Array:
function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
$sort_col = array();
foreach ($arr as $key=> $row) {
$sort_col[$key] = $row[$col];
}
array_multisort($sort_col, $dir, $arr);
}
array_sort_by_column($filter[][][], 'variant_name');
My target is modify array by sorting 'variant_name' to 'Apple', 'Banana', 'Carrot' accordingly keeping the array structure.
It's a working code tested from given examples.
Note that my codes still can be optimized, etc. Just take it as my advice.
TL;DR = Use usort().
function mySort($a,$b)
{
$av = "";
$bv = "";
foreach($a as $ak)
$av = $ak['variant_name'];
foreach($b as $bk)
$bv = $bk['variant_name'];
if($av[0] < $bv[0])
return false;
else return true;
}
How to use it? You have to specify which first level array to sort.
usort($filter['2413'],"mySort");
Then the result I got is:
Array
(
[2413] => Array
(
[0] => Array
(
[87] => Array
(
[sub_id] => 2
[variant_id] => 87
[variant_name] => Apple
)
)
[1] => Array
(
[81] => Array
(
[sub_id] => 1
[variant_id] => 81
[variant_name] => Banana
)
)
[2] => Array
(
[32] => Array
(
[sub_id] => 3
[variant_id] => 32
[variant_name] => Carrot
)
)
)
)

Sort array by sub array

I have array:
$array = array(array('2012-12-12', 'vvv'), array('2012-12-14', 'df'),array('2012-12-10', 'vvv'),array('2012-12-11', 'vvv'));
Array
(
[0] => Array
(
[0] => 2012-12-12
[1] => vvv
)
[1] => Array
(
[0] => 2012-12-14
[1] => df
)
[2] => Array
(
[0] => 2012-12-10
[1] => vvv
)
[3] => Array
(
[0] => 2012-12-11
[1] => vvv
)
)
http://codepad.org/gxw2yKMU
is possible to sort this with dates DESC? For this example should be:
$array[1] //2012-12-14
$array[0] //2012-12-12
$array[3] //2012-12-11
$array[2] //2012-12-10
For me the best way is use embedded functions for PHP, but how? :)
You can use usort with a custom function. If you're on PHP < 5.3 you'll need a named function rather than, as I have, an anonymous one.
$array = array(
array('2012-12-12', 'vvv'),
array('2013-12-14', 'df'),
array('2012-12-14', 'df'),
array('2012-12-10', 'vvv'),
array('2012-12-11', 'vvv')
);
usort($array, function($a, $b) {
if ($a[0] == $b[0]) return 0;
return ($a > $b) ? -1 : 1;
});
print_r($array);
You should be able to use usort
usort( $array, 'sortFunction' );
function sortFunction( $a, $b ) {
if( $a[0] == $b[0] )
return 0;
return ( $a[0] > $b[0] ? return -1 : 1 );
}
You can use array_multisort() :
foreach ($array as $key => $row) {
$dates[$key] = $row[0];
}
array_multisort($dates, SORT_DESC, $array);
First, you put out all dates in a new array. Then, array_multisort() will sort the second array ($array) in the same order than the first ($dates)

Array sort in PHP

How can I sort a 2D array in PHP.
I want to sort on date, Array is in this format :
[result] => Array
(
[0] => Array
(
[link] => http://local/node/0
[date] => 13158505310
)
[1] => Array
(
[link] => http://local/node/1
[date] => 13158505311
)
[2] => Array
(
[link] => http://local/node/2
[date] => 13158505312
Use usort:
usort( $array, function( $a, $b ){ return $a["date"] - $b["date"]; } );
Use this
function sortByDateDesc($a, $b) {
return strcmp($a["date"], $b["date"]);
}
function sortByDateAsc($a, $b) {
if ($a['date'] == $b['date']) {
return 0;
}
return ($a['date'] > $b['date']) ? -1 : 1;
}
usort($array, 'sortByDateDesc'); //Descending order
//usort($array, 'sortByDateAsc'); //Asceding order
Use http://nl.php.net/manual/en/function.usort.php
You could also try multisort http://www.php.net/manual/en/function.array-multisort.php
may be this code helpful to you....
// Obtain a list of columns
foreach (data as key => row) {
links[key] = row['link'];
dates[key] = row['date'];
}
// Sort the data with link descending, date ascending
// Add $data as the last parameter, to sort by the common key
array_multisort(link, SORT_DESC, date, SORT_ASC, data);

Categories