PHP Combine Array and Sorting It

311

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?

760

Answer

Solution:

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)
}
20

Answer

Solution:

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>";
}
?>
391

Answer

Solution:

useasort inplace ofrsort

<?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>";
}
?>

People are also looking for solutions to the problem: javascript - slick slider creating last slide empty Angular JS?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.