This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 4 years ago.
I have an array like this, how can I sort by "name"
Array (
[0] => Array (
[id] => 1
[name] => status_category_confide
)
[1] => Array (
[id] => 2
[name] => status_category_love
)
[2] => Array (
[id] => 3
[name] => status_category_household
)
[3] => Array (
[id] => 4
[name] => status_category_family
)
[4] => Array (
[id] => 5
[name] => status_category_friends
)
[5] => Array (
[id] => 6
[name] => status_category_colleague
)
[6] => Array (
[id] => 7
[name] => status_category_work
)
[7] => Array (
[id] => 8
[name] => status_category_ambition
)
)
I've tried using the "sort" function but it doesn't work
$get_status_mood=mysqli_query($con, "select id, name from category");
while ($gsm=mysqli_fetch_array($get_status_mood)) {
//array_push($status_category, constant($gsm['name']));
$status_category[] = array(
"id"=>$gsm['id'],
"name"=>$gsm['name']
);
}
sort($status_category);
for ($i=0; $i<count($status_category); $i++) {
echo"<option value='".$status_category[$i]['id']."'>".$status_category[$i]['name']."</option>";
}
I want to display the results in the order of the name
Try the SQL order by option
$get_status_mood=mysqli_query($con, "select id, name from category order by name asc");
You can sort it using array_column and array_multisort functions.
$keys = array_column($array, 'name');
array_multisort($keys, SORT_ASC, $array);
You can try it with usort this sort an array by values using a user-defined comparison function
function cmp($a, $b)
{
return strcmp($a["name"], $b["name"]);
}
usort($vc_array, "cmp");
$a = array();
$a[] = array('id' => 1, 'name' => 'status_category_confide');
$a[] = array('id' => 2, 'name' => 'status_category_love');
$a[] = array('id' => 3, 'name' => 'status_category_household');
function cmp($x, $y) {
if (strcmp($x['name'], $y['name']) == 0) {
return 0;
}
return (strcmp($x['name'], $y['name']) < 0) ? -1 : 1;
}
usort($a, "cmp");
print_r($a);
Related
This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 10 months ago.
I have two arrays:
Array
(
[0] => 5
[1] => 4
)
Array
(
[0] => BMW
[1] => Ferrari
)
And I would like to have that result. Merge the values with the same key
Array
(
[0] => Array
(
[0] => 5
[1] => BMW
)
[1] => Array
(
[0] => 4
[1] => Ferrari
)
)
How could I do that? Is there any native PHP function that does this? I tried array_merge_recursive and array_merge but did not get the expected result
As to #splash58 comment:
You can use array-map. Here an example:
$array = [["5", "4"], ["BMW", "Ferrari"]];
$res = array_map(null, ...$array);
Now res will contain:
Array
(
[0] => Array
(
[0] => 5
[1] => BMW
)
[1] => Array
(
[0] => 4
[1] => Ferrari
)
)
If the array in 2 different var you can use:
$res= array_map(null, ["5", "4"], ["BMW", "Ferrari"]);
<?php
$a = array();
$a[0] = '5';
$a[1] = '4';
$b = array();
$b[0] = 'BMW';
$b[1] = 'Ferrari';
merge_by_key($a, $b);
function merge_by_key($a, $b){
$c = array();
fill_array($c,$a);
fill_array($c,$b);
print_r($c);
}
function fill_array(&$c, $a) {
foreach ($a as $key => $value){
if(isset($c[$key])) {
array_push($c[$key], $value);
} else {
$c[$key] = array($value);
}
}
}
Output:
Array
(
[0] => Array
(
[0] => 5
[1] => BMW
)
[1] => Array
(
[0] => 4
[1] => Ferrari
)
)
You can use array_map with null as the first argument (there is an example in the manual), to get your desired result:
<?php
$nums = [0 => 5, 1 => 4];
$cars = [0 => 'BMW', 1 => 'Ferrari'];
var_export(array_map(null, $nums, $cars));
Output:
array (
0 =>
array (
0 => 5,
1 => 'BMW',
),
1 =>
array (
0 => 4,
1 => 'Ferrari',
),
)
Note that the following input would give the same result:
$nums = ['puff' => 5, 'powder' => 4];
$cars = ['powder' => 'BMW', 'puff' => 'Ferrari'];
It is the order, not the keys, that determine the pairings in the result when using array_map as above.
To associate by key using foreach (note order of $cars):
<?php
$nums = [0 => 5, 1 => 4];
$cars = [1 => 'Ferrari', 0 => 'BMW'];
foreach($nums as $k => $num)
$result[] = [$num, $cars[$k]];
var_export($result);
Results also in the desired output.
I have an array called "playersArray" that looks like this:
Array (
[0] => Array ( [name] => Joe [holders] => 0 )
[1] => Array ( [name] => Bob [holders] => 100 )
[2] => Array ( [name] => Jake [holders] => 100 )
[3] => Array ( [name] => Mike [holders] => 100 )
[4] => Array ( [name] => Tim [holders] => -0.0145 )
[5] => Array ( [name] => Frank[holders] => 100 )
[6] => Array ( [name] => Scott [holders] => 0.0583 )
[7] => Array ( [name] => Doug[holders] => 0.1308 )
[8] => Array ( [name] => Tommy [holders] => 0.2516 )
[9] => Array ( [name] => Eric [holders] => 100 )
)
I have a function to sort this array by the "holders" value:
function compareHolders($a, $b) {
$aPoints < $a['holders'];
$bPoints < $b['holders'];
return strcmp($aPoints, $bPoints);
}
I loop through another array to create this array:
foreach ($players as $player) {
$player['name'] = $athlete['name'];
$player['holders'] = $total_result_yesterday;
$playersArray[] = $player;
}
I am trying to sort the array by "holder" value:
usort($playersArray, 'compareHolders');
print_r($playersArray);
Finally, I am trying to get the 5 highest and 5 lowest "holder" values in the newly sorted array:
$first_5_players = array_slice($playersArray, 0, 5, true);
$last_5_players = array_slice($playersArray, -5);
However, the sorting is not working correctly. The values due not show in sequential order as desired. How can I get the sorting to work correctly? Thank you!
your sorting function compareHolders is not correct. $aPoints and $bPoints are not defined. Since values for holders key are numeric you can use the comparision operators. Try doing following:
function compareHolders($a, $b) {
if ($a['holders'] == $b['holders']) {
// return 0 if equal
return 0;
}
return ($a['holders'] > $b['holders']) ? -1 : 1;
}
You are not actually comparing the two values in compareHolders(), because you're not declaring $aPpoints and $bPoints.
This should work:
function compareHolders($a, $b) {
$aPoints = $a['holders'];
$bPoints = $b['holders'];
return strcmp($aPoints, $bPoints);
}
or alternatively you could just return:
return strcmp($a['holders'], $b['holders']);
And then you could get rid of the strcmp(), since you're not comparing strings.
This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 7 years ago.
I have this array:
Array (
[order] => Array ( [0] => 2 [1] => 1 )
[eventid] => Array ( [0] => id_1 [1] => id_2 )
)
Now I would like to get:
Array (
[order] => Array ( [0] => 1 [1] => 2 )
[eventid] => Array ( [0] => id_2 [1] => id_1 )
)
Basically I would like to sort arrays by value of order.
You will need to use the usort function to be able to do this. (See the documentation)
I would recommend another Array structure though, something like this:
Array (
[0] => Array ( [order] => 2, [eventid] => id_x )
[1] => Array ( [order] => 1, [eventid] => id_y )
)
Then you could a function like this one to sort your array (PHP 5.3 or greater):
function array_sort_by(&$array, $key, $descending = false) {
$sortByKey =
function ($a, $b) use ($key, $descending) {
if ($a[$key] === $b[$key]) {
return 0;
}
$return = $a[$key] < $b[$key] ? -1 : 1;
return ($descending ? -1 * $return : $return);
};
usort($array, $sortByKey);
}
You would then call the following:
array_sort_by($yourArray, 'order');
You can use asort. While it can cover your case, usort might be a better solution in the long run.
$arr = Array (
"order" => Array ( 0 => 6, 1 => 1,2=>43),
"eventid" => Array ( 0 => 5, 1 => 1,2=>54,3=>0)
);
foreach ($arr as $key => &$value) {
asort($value);
}
This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 8 years ago.
I have array $leaderboard. Which contains following data
Array
(
[0] => Array
(
[name] => ABC
[time_taken] => 01:46:56
)
[1] => Array
(
[name] => DEF
[time_taken] => 00:21:54
)
[2] => Array
(
[name] => MNO
[time_taken] => 00:34:14
)
[3] => Array
(
[name] => PQR
[time_taken] => 00:09:17
)
[4] => Array
(
[name] => XYZ
[time_taken] => 00:34:14
)
[5] => Array
(
[name] => STR
[time_taken] => 00:34:14
)
[6] => Array
(
[name] => LOK
[time_taken] => 17:53:58
)
}
I tried to sort the array on basis of time. Its working fine if time values not duplicate using ksort. But for duplicated time it only shows on record from that
<h4>function aasort (&$array, $key) {
<br>
$sorter=array();<br>
$ret=array();<br>
reset($array);<br>
foreach ($array as $ii => $va) {<br>
$sorter[$ii]=$va[$key];<br>
<br> }
asort($sorter);<br>
foreach ($sorter as $ii => $va) <br>{
$ret[$ii]=$array[$ii];
}
$array=$ret;<br>
}
aasort($your_array,"order");</h4>
Try this code,
<?php
$sortArray = array(array('name' => 'ABC',
'time_taken' => '01:46:56'),
array('name' => 'DEF',
'time_taken' => '00:21:54'),
array('name' => 'MNO',
'time_taken' => '00:34:14'),
array('name' => 'PQR',
'time_taken' => '00:09:17'),
array('name' => 'XYZ',
'time_taken' => '00:34:14'),
array('name' => 'LOK',
'time_taken' => '17:53:58'));
print_r($sortArray);
foreach ($sortArray as $key => $row) {
$sorting[$key] = $row['time_taken'];
}
array_multisort($sorting, SORT_ASC, $sortArray);
print_r($sortArray);
You can define your own sorting function and use uksort.
More about that: uksort
give it a try please..
function cmp( $a, $b ) {
if( strtotime($a['time_taken']) == strtotime($b['time_taken']) ){ return 0 ; }
return (strtotime($a['time_taken']) < strtotime($b['time_taken'])) ? -1 : 1;
}
usort($leaderboard,'cmp');
reference https://stackoverflow.com/a/9001655/829533
This question already has answers here:
How do I sort a multidimensional array by one of the fields of the inner array in PHP? [duplicate]
(8 answers)
Closed last year.
Yes, I have searched and tried many techniques, but nothing seems to work. Here is my array:
Array
(
[0] => stdClass Object
(
[id] => 119
[name] => Business3
[start_date] => 1338789600
[end_date] => 1354604400
)
[1] => stdClass Object
(
[id] => 153
[name] => Business1
[start_date] => 1338962400
[end_date] => 1370498400
)
[2] => stdClass Object
(
[id] => 135
[name] => Business2
[start_date] => 1339653600
[end_date] => 1356937200
)
)
I basically want to sort this by the name key, but every function I've tried on Stackoverflow doesn't seem to work, as in, I get a blank page with no error.
I tried this:
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(json_decode(json_encode($businesses), true), 'name');
But that didn't work.
Any ideas?
You're almost right, but $row[$col] tries to access the objects like an array. You want something like $row->{$col} instead. Here's a simpler, working example:
$db = array(
0 => (object) array('name' => 'Business3'),
1 => (object) array('name' => 'Business2'),
2 => (object) array('name' => 'Business1')
);
$col = 'name';
$sort = array();
foreach ($db as $i => $obj) {
$sort[$i] = $obj->{$col};
}
$sorted_db = array_multisort($sort, SORT_ASC, $db);
print_r($db);
Outputs:
Array
(
[0] => stdClass Object
(
[name] => Business1
)
[1] => stdClass Object
(
[name] => Business2
)
[2] => stdClass Object
(
[name] => Business3
)
)
usort($array, function($a, $b) {
return strcmp($a->name, $b->name);
});
You should use usort...
So you define a function that compares two objects (by the name field) and then run usort on the array, passing in the function as the second argument.
Something like this:
function cmp($a, $b)
{
if ($a["name"] == $b["name"]) {
return 0;
}
return ($a["name"] < $b["name"]) ? -1 : 1;
}
usort ($my_array, "cmp");
var_dump($my_array);
Hope that helps!
Ben