Hello everyone!) In php is not strong) got such a task: write the sort function of the array $ TH, so that it was possible to file the key name at the input and it sorted the array $ TH by its value Tell me how you can solve the problem?

$m = array('a'=>'Honda','b'=>'Hummer','c'=>'BMW','d'=>'Toyota'); $s = array('a'=>'AH','b'=>'TU-144','c'=>'Boing','d'=>'СУ'); $t = array('a'=>'Тигр','b'=>'Пантера','c'=>'Т-34','d'=>'Волга'); $k = array('a'=>'Кузнецов','b'=>'Ямато','c'=>'Ясень','d'=>'Петропавловск'); $TH = array($m, $s, $t, $k); 
  • What does the на вход подать имя ключа и он по его значению отсортировал массив $TH mean на вход подать имя ключа и он по его значению отсортировал массив $TH ? how should it look like? - Alexey Shimansky
  • @ Alexey Shimansky, like this, only on php, not on js: f = (arr, key) => arr.sort((x, y) => (x[key]>y[key]) - (x[key]<y[key])); f([{a:7},{a:3},{a:1}], 'a') f = (arr, key) => arr.sort((x, y) => (x[key]>y[key]) - (x[key]<y[key])); f([{a:7},{a:3},{a:1}], 'a') - Qwertiy

1 answer 1

If you mean by the keys a,b,c,d , then so?

 $sortBy = "b"; usort($TH, function($l, $r) use ($sortBy){ return strcmp($l[$sortBy], $r[$sortBy]); }); print_r($TH); 
  • @ br3t are artifacts of copying code from mcedit , corrected - teran