Thursday 30 August 2018

PHP Sort an associative array with a custom order

This question already has an answer here:

  • How can I sort arrays and data in PHP? 7 answers
How can we sort an associative array with custom order? My array look like this
Array
(
    [pa_color] => Array
        (
            [name] => pa_color
            [value] =>
            [position] => 0
            [is_visible] => 1
            [is_variation] => 1
            [is_taxonomy] => 1
        )

    [pa_dimension] => Array
        (
            [name] => pa_dimension
            [value] =>
            [position] => 1
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_travel-duration] => Array
        (
            [name] => pa_travel-duration
            [value] =>
            [position] => 2
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_travel-type] => Array
        (
            [name] => pa_travel-type
            [value] =>
            [position] => 3
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_travelling-with] => Array
        (
            [name] => pa_travelling-with
            [value] =>
            [position] => 4
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_volume] => Array
        (
            [name] => pa_volume
            [value] =>
            [position] => 5
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_weight] => Array
        (
            [name] => pa_weight
            [value] =>
            [position] => 6
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

)

and i want this array is like pa_travel-duration first pa_volume second ?? I know there is a native php function usort but i could not understand this.

This will do the work, but im pretty sure there's much better ways to do it:
Code:
$array = array("pa_color" => "color",
              "pa_dimension" => "dimension",
              "pa_travel-duration" => "Random Stuff: " . rand(100,999),
              "pa_volume" => "volumen"
              );
$tmp = array("pa_travel-duration" =>  $array["pa_travel-duration"],
            "pa_volume" =>  $array["pa_volume"],
);

unset($array["pa_travel-duration"], $array["pa_volume"]);
$array = array_merge($tmp,$array);

print_r($array);

Result:
Array
(
    [pa_travel-duration] => Random Stuff: 127
    [pa_volume] => volumen
    [pa_color] => color
    [pa_dimension] => dimension
)

Take care because if the array doesn't have the proper key it will throw an error, you need to add few checks there.

0 comments:

Post a Comment