How to sort an array of associative arrays by value of a given key in PHP?
You are right, the function you're looking for is array_multisort()
.
Here's an example taken straight from the manual and adapted to your case:
$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
As of PHP 5.5.0 you can use array_column()
instead of that foreach:
$price = array_column($inventory, 'price');
array_multisort($price, SORT_DESC, $inventory);
Array sorting by key value in php
Use usort.
E.g
function sortByAmount($x, $y) {
return $x['amount'] - $y['amount'];
}
usort($array, 'sortByAmount');
echo "<pre>"; print_r($array);
How to sort an Array of Associative Arrays by a Value
use array_multisort method
$arr = array(
array('name' => 'John' , 'total' => '33'),
array('name' => 'Robert' , 'total' => '66'),
array('name' => 'John' , 'total' => '22'),
);
$total = array();
foreach ($arr as $key => $row)
{
$total[$key] = $row['total'];
}
array_multisort($total, SORT_DESC, $arr);
How to sort associative array by its value using PHP?
uasort() function is what you're looking for.
uasort($data, function($a, $b) { return strcasecmp($a['name'], $b['name']); });
You should take a look on usort() and uksort() doc for examples of how user-defined comparison functions works.
PHP - sort array by array key
Using usort
:
high to low
usort($input, function ($a, $b) {return $a['custom_price'] < $b['custom_price'];});
print_r( $input );
low to high
usort($input, function ($a, $b) {return $a['custom_price'] > $b['custom_price'];});
print_r( $input );
http://php.net/manual/en/function.usort.php
PHP array sorting associative array using a specific key value
proper use of usort
See also: Sort Multi-dimensional Array by Value
your example is invalid
Expected first entry in result: 0 => '6'
Possible interpretation odbyx-index == id-index
Should indices in odbyx
match to indices in id
?
i.e.: $array['id'][3]
should be sorted by $array['odbyx'][3]
If this is the case, then your provided code should either yield 0 => '8'
for the first index (odbyx 1 higher-priority than 3), or 0 => '1'
(3 is higher).
Possible interpretation odbyx-index == id-value
Should the index in odbyx
match to the id values in id
?
i.e.: The value of $array['odbyx'][1]
determines the sort for $array['id'][6] = '1'
In this case, the result should be 0 => '2'
None of these possible interpretations even match the very first result in your example. The lesson here is specification, i.e.: carefully define and describe the specific conditions required to solve your problem, on stackoverflow or anywhere else.
Here's a place to start
Since the problem you are asking to be solved is complex, poorly defined, would require a significant amount of coding and testing, and has significant performance implications, I'll leave you with this tidbit of a solution to one of the impossible interpretations above. Good luck.
Class SimpleSorter
{
private $orderBy;
private $sortMe;
public static function sortByIndexedOrderField(array $sortMe, array $byMe)
{
$sorter = new self($sortMe);
return $sorter->applyIndexedOrder($byMe);
}
public function __construct(array $sortMe)
{
$this->sortMe = $sortMe;
}
public function applyIndexedOrder(array $byMe): array
{
$this->orderBy = $byMe;
$keys = array_keys($this->sortMe);
// sort, first by odbyx, then by value
usort($keys, function($a,$b){
$odbyx = 0;
if (array_key_exists($a, $this->orderBy) && array_key_exists($b, $this->orderBy)) {
$odbyx = $this->orderBy[$b] <=> $this->orderBy[$a];
}
if (0 !== $odbyx) {
return $odbyx;
}
return $this->sortMe[$a] <=> $this->sortMe[$b];
});
// reorder by new key order
$result = [];
foreach($keys as $key) {
$result[$key] = $this->sortMe[$key];
}
return $result;
}
}
$array = [];
$array["id"] = [
0 => '8',
1 => '7',
2 => '3',
3 => '6',
4 => '5',
5 => '2',
6 => '1',
];
$array["odbyx"] = [
0 => 1,
1 => 2,
2 => 3,
3 => 2,
4 => 3,
5 => 3,
6 => 3,
];
$idsSorted = SimpleSorter::sortByIndexedOrderField($array["id"], $array["odbyx"]);
print_r($idsSorted);
Filter associative array to keep elements when their value is greater than their neighboring elements' values
You should change the condition if you really want to get border items. But an approach could be to use the array of keys to get prev and next items
$array = array('a' => 0, 'b' => 2, 'c' => 1, 'd' => 2, 'e' => 3);
$keys = array_keys($array);
$b = array_filter($array, function($v, $k) use($array, $keys) {
$k = array_search($k, $keys);
return $k > 0 && $v > $array[$keys[$k-1]] && $k + 1 < count($keys) && $v > $array[$keys[$k+1]];
}, ARRAY_FILTER_USE_BOTH );
print_r($b);
Related Topics
How to Validate an Email Address in PHP
What Is the Most Accurate Way to Retrieve a User'S Correct Ip Address in PHP
Is There a Code Obfuscator For PHP
Sending Email With Gmail Smtp With Codeigniter Email Library
How to With MySQLi Make a Query With Like and Get All Results
MySQL Connection Not Working: 2002 No Such File or Directory
How to Pad Single-Digit Numbers With a Leading 0
Unicode Character in PHP String
How to Get an Array of Specific "Key" in Multidimensional Array Without Looping
How to Access Object Properties With Names Like Integers or Invalid Property Names
Sort Array of Objects by One Property
Parse Error: Syntax Error, Unexpected End of File in My PHP Code
Call to a Member Function Bind_Param() on a Non-Object