PHP Sort Array by Subarray Value

PHP Sort Array By SubArray Value

Use usort.

function cmp_by_optionNumber($a, $b) {
return $a["optionNumber"] - $b["optionNumber"];
}

...

usort($array, "cmp_by_optionNumber");

In PHP ≥5.3, you should use an anonymous function instead:

usort($array, function ($a, $b) {
return $a['optionNumber'] - $b['optionNumber'];
});

Note that both code above assume $a['optionNumber'] is an integer. Use @St. John Johnson's solution if they are strings.


In PHP ≥7.0, use the spaceship operator <=> instead of subtraction to prevent overflow/truncation problems.

usort($array, function ($a, $b) {
return $a['optionNumber'] <=> $b['optionNumber'];
});

How to sort array based on subarray value in PHP

Try -

usort($array, function($a, $b) {
return $a['Product']['name'] > $b['Product']['name'];
});

usort()

PHP sort subarray value?

Simple enough:

foreach($arr as &$v) {
sort($v);
}

The &$v allow the values to be iterated over by reference, allowing modification inside the foreach loop (and thus sorting of each subarray).

PHP - Sort Array By SubArray Value By Maintaining original Array key

$arr being your array:

//obtain list of values to sort by
foreach ($arr as $id => $value) {
$names[$id] = $value['name'];
}
$keys = array_keys($arr);
array_multisort(
$names, SORT_ASC, SORT_NUMERIC, $arr, $keys
);
$result = array_combine($keys, $arr);

You were probably missing the last step combining the array with given keys.

PHP - Sort array by subarray value based on a second array

This should do the trick

usort($data, function($a, $b) use ($gids)
{
$posA = array_search($a['group_id'], $gids);
if ($posA === false) {
$posA = 9999;
}

$posB = array_search($b['group_id'], $gids);
if ($posB === false) {
$posB = 9999;
}

return $posA - $posB;
});

If found in the array of $gids, the sorting of $gids will be used, else the elements will stay in the order they're given in.

The return I'm getting is the following:

array:5 [▼ 0 => array:3 [▼
"id" => 8
"name" => "Baz"
"group_id" => 7 ] 1 => array:3 [▼
"id" => 10
"name" => "DEF"
"group_id" => 65 ] 2 => array:3 [▼
"id" => 5
"name" => "Foo"
"group_id" => 1 ] 3 => array:3 [▼
"id" => 6
"name" => "Bar"
"group_id" => 1 ] 4 => array:3 [▼
"id" => 9
"name" => "ABC"
"group_id" => 2 ] ]

PHP sort array alphabetically using a subarray value

Here is your answer and it works 100%, I've tested it.

<?php
$a = Array(
1 => Array(
'name' => 'Peter',
'age' => 17
),
0 => Array(
'name' => 'Nina',
'age' => 21
),
2 => Array(
'name' => 'Bill',
'age' => 15
),
);
function compareByName($a, $b) {
return strcmp($a["name"], $b["name"]);
}
usort($a, 'compareByName');
/* The next line is used for debugging, comment or delete it after testing */
print_r($a);

Sort Array Index by SubArray Value

You should probably use array_multisort()

array_multisort(
array_column( $AsocContData[$s_list_100], 'Mark' ), // sort by the Mark sub-array value first
SORT_ASC, // ascending
SORT_NUMERIC, // treat data as numeric
array_keys( $AsocContData[$s_list_100] ), // secondly, sort by the array indexes
SORT_ASC, // ascending
SORT_NUMERIC, // treat indexes as numeric
$AsocContData[$s_list_100] // this array will be sorted in place and by reference
);

var_dump( $AsocContData[$s_list_100] );

Input:

$AsocContData[$s_list_100] = array(
'01081' => Array(
'id' => 2,
'Mark' => 420,
'lastUpdated' => '2010-03-17 15:44:12'
),
'00358' => Array(
'id' => 6,
'Mark' => 500,
'lastUpdated' => '2010-03-17 15:44:12'
),
'00277' => Array(
'id' => 3,
'Mark' => 400,
'lastUpdated' => '2010-03-17 15:44:12'
),
'00357' => Array(
'id' => 1,
'Mark' => 500,
'lastUpdated' => '2010-03-17 15:44:12'
)
);

Output:

Array
(
[00277] => Array
(
[id] => 3
[Mark] => 400
[lastUpdated] => 2010-03-17 15:44:12
)

[01081] => Array
(
[id] => 2
[Mark] => 420
[lastUpdated] => 2010-03-17 15:44:12
)

[00357] => Array
(
[id] => 1
[Mark] => 500
[lastUpdated] => 2010-03-17 15:44:12
)

[00358] => Array
(
[id] => 6
[Mark] => 500
[lastUpdated] => 2010-03-17 15:44:12
)

)

Sort array by highest possible subarray value

Okay, that's what you need to do - find max score in each grouping and store a lookup [grouping -> score], then sort this lookup array preserving keys and build new array:

$lookup = [];
foreach ($source_array as $key => $grouping) {
$max = 0;
foreach ($grouping as $item) {
if ($max < $item['_score']) {
$max = $item['_score'];
}
}
$lookup[$key] = $max;
}

// sort `$lookup` preserving keys
arsort($lookup);

$sorted_array = [];
foreach ($lookup as $key => $max) {
$sorted_array[$key] = $source_array[$key];
}

PHP - Sort array by value in subarray - DESC and ASC

The answer you link to tells you exactly what you need to do, doesn't it? The only thing I would add is that you might appreciate the strnatcmp function for comparing strings rather than numbers. So you'd have:

function cmp_by_clientType($a, $b) {
return strnatcmp($a["client_type"], $b["client_type"]);
}

usort($array, "cmp_by_clientType");

When you say the answer you link to doesn't work, what is the problem you're experiencing?

EDIT

For asc and desc the simplest would be to have two sort functions, so for DESC you'd have the same function but you swap $a and $b:

function cmp_by_clientType_DESC($a, $b) {
return strnatcmp($b["client_type"], $a["client_type"]);
}

If you find this inelegant, you could maybe pass a boolean to the compare function, but that's more tricky. You can read more here:

Pass extra parameters to usort callback

PHP: Sort Array by subarray values (descending)

You could sum your data using array_sum() , or array_max() :

function func($a, $b) {
$suma = array_sum($a['score']); // or array_max
$sumb = array_sum($b['score']); // or array_max
if ($suma == $sumb) { return 0; }
return ($suma < $sumb) ? 1 : -1 ;
// or just : return $suma <=> $sumb ; // As of PHP 7
}
uasort($main_array, 'func');
print_r($main_array);

As pointed by @deceze, here is a shorter function using difference between values instead of comparing the three states (see comments below) :

function func($a, $b) {
return array_sum($b['score']) - array_sum($a['score']);
}


Related Topics



Leave a reply



Submit