简体   繁体   中英

PHP Combine Array and Sorting It

I'm new in PHP array, and I have a multidimensional array like this: $person['id'] = $value; My sample data is like this:

$person[1]=110
$person[2]=200
$person[3]=300
$person[4]=100
$person[5]=220

Right now, I want to sort it by its value, so my array should be like these:

$person[3]=300
$person[5]=220
$person[2]=200
$person[1]=110
$person[4]=100

After this, I want to print it numbers of sorting... So my result would be like these:

$person[3]=1
$person[5]=2
$person[2]=3
$person[1]=4
$person[4]=5

Here's my full code:

$person = array();
$person[1]=110;
$person[2]=200;
$person[3]=300;
$person[4]=100;
$person[5]=220;

rsort($person);
foreach($person as $x => $x_value) {
   echo "Key=" . $x . ", Value=" . $x_value;
   echo "<br>";
}

And that's it, I'm stuck to change the value to what I want. Anyone know how to create a code that I wanted?

use asort() method of php for sorting array

http://php.net/manual/en/function.asort.php

<?php
$person = array();
$person[1]=110;
$person[2]=200;
$person[3]=300;
$person[4]=100;
$person[5]=220;
asort($person);
foreach($person as $x => $x_value) {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
}
?>

use asort inplace of rsort

<?php
$person = array();
$person[1]=110;
$person[2]=200;
$person[3]=300;
$person[4]=100;
$person[5]=220;

asort($person);
foreach($person as $x => $x_value) {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
}
?>

Use arsort : Sorts an array in reverse order and maintain index association

<?PHP
$person = array();
$person[1]=110;
$person[2]=200;
$person[3]=300;
$person[4]=100;
$person[5]=220;

arsort($person);
$i=0;
foreach($person as &$p){
    $p=++$i;
}

var_dump($person);

so your output will be:

array(5) {
  [3]=>
  int(1)
  [5]=>
  int(2)
  [2]=>
  int(3)
  [1]=>
  int(4)
  [4]=>
  &int(5)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM