Home > Net >  sort array by number of child of a key
sort array by number of child of a key

Time:01-17

i have something like this to check how many same contacts a user have compared to the others, so I saved it under duplicate number. I want to ask is there anyway to sort this by calculating the number of child in "duplicate_number"? in PHP?

         {
            "user_id": 134,
            "duplicate_number": [
                {
                    "contact_name": "A",
                    "contact_no": "2341211",
                    "compared_name": "B"
                },
                {
                    "contact_name": "C",
                    "contact_no": "0236232",
                    "compared_name": "D"
                },
                {
                    "contact_name": "E",
                    "contact_no": "32326",
                    "compared_name": "F"
                }
            ]
        },
        {
            "user_id": 119,
            "duplicate_number": []
        },
        {
            "user_id": 108,
            "duplicate_number": [
                {
                    "contact_name": "G",
                    "contact_no": "053183",
                    "compared_name": "H"
                }
            ]
        },

CodePudding user response:

You can use usort for this and base it on the number of items in the duplicate_number lists, e.g.:

$list = [ 
    [
        "user_id" => 134,
        "duplicate_number" => [
            [ "contact_name"=> "A", "contact_no" => "2341211","compared_name" => "B" ],
            [ "contact_name" => "C", "contact_no" => "0236232", "compared_name" => "D" ],
            [ "contact_name" => "E", "contact_no" => "32326", "compared_name" => "F" ]
        ]
    ],
    [
        "user_id"=> 119,
        "duplicate_number"=> []
    ],
    [
        "user_id"=> 108,
        "duplicate_number"=> [
            [ "contact_name"=> "G", "contact_no"=> "053183", "compared_name"=> "H" ]
        ]
    ]
];

function cmp( $a, $b) {
    if ( count( $a['duplicate_number'] ) === count( $b['duplicate_number'] ) ) {
        return 0;
    }
    return count( $a['duplicate_number'] ) < count( $b['duplicate_number'] ) ? -1 : 1;
}

usort( $list, 'cmp' );
print_r( $list );
  •  Tags:  
  • Related