Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Jun 2008
    Posts
    355
    Thanks
    6
    Thanked 27 Times in 27 Posts

    Stupid Beginner Array Sort Question

    I have an array
    PHP Code:
    $array['A']=5;
    $array['B']=2;
    $array['C']=3
    How to achieve the following sort of $array? (sort by it's value)
    PHP Code:
    $array['B']
    $array['C']
    $array['A'
    and of course the other way

    PHP Code:
    $array['A']
    $array['C']
    $array['B'


    Usually i do it a complicated way (by foreach, init new array and and so on). But there have to be a more easy way right?

    Thats my current function by the way
    PHP Code:
    function sortByKey($arr=false,$sort='desc'){
        foreach(
    $arr as $name=>$val){
            
    $n[].=$name;
            
    $v[].=$val;
        }
        if(
    $sort==='asc'){
            
    array_multisort($v,SORT_ASC,$n);
        }else{
            
    array_multisort($v,SORT_DESC,$n);
        }
        for(
    $i=0$i<count($n); $i++){
        
    $ba[$n[$i]]=$v[$i];}
        return 
    $ba;

    which does exactly what i need. But there must be a better way.
    Last edited by Labrar; Jan 18th, 2019 at 10:44 PM.
    I never ever read PM's unless it's an job offer. So save your time for regular questions in the forum. I never ever take friendship offers. We are not on facebook here.(It's stupid on facebook too). Friendship? Do i know you? Did we ever had a beer together? Thats really stupid. Sorry.

  2. #2
    Senior Coder benanamen's Avatar
    Join Date
    Oct 2015
    Posts
    1,588
    Thanks
    10
    Thanked 161 Times in 156 Posts
    PHP Code:
    <?php
    $array
    ['A']=5;
    $array['B']=2;
    $array['C']=3;


    asort($array);
    echo 
    '<pre>';
    print_r(array_keys($array));
    echo 
    '</pre>';

    arsort($array);
    echo 
    '<pre>';
    print_r(array_keys($array));
    echo 
    '</pre>';
    To save time, lets just assume I am almost never wrong.

    The XY Problem
    The XY problem is asking about your attempted solution (X) rather than your actual problem (Y). This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.

    Make A Donation https://www.paypal.me/KevinRubio

  3. Users who have thanked benanamen for this post:

    Labrar (Jan 19th, 2019)


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •