Home > Blockchain >  Sort multidimensional array WITHOUT KEYNAMES in PHP, case insensitive
Sort multidimensional array WITHOUT KEYNAMES in PHP, case insensitive

Time:06-11

I have an array like this

Array
(
    [0] => Array
        (
            [0] => space
            [1] => Venus
            [2] => NASA
            [3] => apple
        )

    [1] => Array
        (
            [0] => link1
            [1] => link2
            [2] => link3
            [3] => link4
        )
)

I want to sort it, case INsensitively, by the [0] term. How can I do this? All answers I've found show how to do this only if the array has keynames.

If that's not clear, I want this:

Array
(
    [0] => Array
        (
            [0] => apple
            [1] => NASA
            [2] => space
            [3] => Venus
        )

    [1] => Array
        (
            [0] => link4
            [1] => link3
            [2] => link1
            [3] => link2
        )
)

If it's easier with keynames, or it can't be done unless there are keynames (which I doubt), how can I modify my original array to contain names "keywords" for [0] and "links" for [1]?

Many thanks.

CodePudding user response:

This code merges the multiple dimension version back into a key/value single array which makes it easy to sort, and then optionally brings it back to multiple dimensions. Demo here: https://3v4l.org/CStsS

$data = [
    ['space', 'Venus', 'NASA', 'apple'],
    ['link1', 'link2', 'link3', 'link4'],
];

// Convert the multiple dimensional array to avsingle
$merged = array_combine(...$data);

// Sort by key
uksort($merged, fn($a, $b) => strcasecmp($a, $b));

var_dump($merged);

// If it needs to be converted back to a multiple dimension array
$data = [
    array_keys($merged),
    array_values($merged),
];

var_dump($data);

CodePudding user response:

$arr = [
    [ 'space', 'Venus', 'NASA', 'apple' ],
    [ 'link1', 'link2', 'link3', 'link4' ]
];

[ $keywords, $links ] = $arr;

array_multisort($keywords, SORT_NATURAL | SORT_FLAG_CASE, $links);

$result = [ 'keywords' => $keywords, 'links' => $links ];

print_r($result);

Note that the line [ $keywords, $links ] = $arr; will only assign the correct values to $keywords and $links if the nested array ares in that order. Also note that it is shorthand for the list function: https://www.php.net/manual/en/function.list.php

  • Related