0

I have an array pr($site_name_with_value) looks like this. This is the result of two combine_array.

Array(
    [Ashuganj PDB] => 720
    [Bagherhat PGCB] => 720
    [Banani_CO] => 720
    [Barapukuria PGCB] => 784
    [Barishal PGCB] => 780
    [Benapole_CO] => 752
    [Bogura RO] => 776
    [Bogura_CO(IS)] => 784 
)

I have tried this to expected output.

$site_name_with_value_order = arsort($site_name_with_value); 
foreach ($site_name_with_value_order as $key => $val) {
    echo "$key = $val\n";
}

It returns an error message Invalid argument supplied for foreach()

First I want to sort them by value descending order. Second if the value is the same then order index by ascending.

I want to get output looks like this. But I don't know how to gain my expected output.

Array(
    [Bogura_CO(IS)] => 784
    [Barapukuria PGCB] => 784
    [Barishal PGCB] => 780
    [Bogura RO] => 776
    [Benapole_CO] => 752 
    [Ashuganj PDB] => 720
    [Bagherhat PGCB] => 720
    [Banani_CO] => 720   
)
3
  • 4
    Those arrays aren't valid. You can't have the same key multiple times. Keys are unique. Commented Oct 6, 2018 at 9:00
  • Also, as stated in the manual, arsort() doesn't return the sorted array. It returns a boolean. It modifies the original array (uses it as a reference). So you're actually passing a boolean to foreach() which is invalid. Commented Oct 6, 2018 at 9:03
  • Array key is unique. But I use it short form. Commented Oct 6, 2018 at 9:58

2 Answers 2

2

First of all, you've created an array with duplicate key which is not a valid way. So when you try to sort the array by value with arsort()- Sort an array in reverse order and maintain index association, but it will return different results for different php version. See the DEMO

$array = array(
   
    'Ash' => 776,
    'Bag' => 720,
    'Ban' => 720,
    'Bar' => 776,
    'Bar' => 780,
    'Ben' => 752,
    'Bog' => 720,
    'Bog' => 780,
    'Bue' => 776,  
);
arsort($array);
print_r($array);
Sign up to request clarification or add additional context in comments.

1 Comment

Good advice for me. And first of all my array already arranged in ascending order.
1

There's no need to assign the

arsort($site_name_with_value); 

in another variable because it will only return to 1. So just loop the

$site_name_with_value 

instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.