-1

I have an array like so

array:2 [▼
  "folder1" => array:3 [▼
    1 => "d1_2.png"
    2 => "d1_1.png"
    3 => "d1_3.png"
  ]
  "folder2" => array:3 [▼
    0 => "d2_2.png"
    1 => "d2_3.png"
    3 => "d2_1.png"
  ]
]

What I am trying to do is sort this array based on the value. So the output should be something like this

array:2 [▼
  "folder1" => array:3 [▼
    0 => "d1_1.png"
    1 => "d1_2.png"
    2 => "d1_3.png"
  ]
  "folder2" => array:3 [▼
    0 => "d1_1.png"
    1 => "d1_2.png"
    2 => "d1_3.png"
  ]
]

All examples I have seen sort based on a key value, but I do not have keys. I have tried several sort functions but none of them seem to sort the array.

How can I sort it based on the array I have?

3
  • Sorry, what I meant was that my keys are indexes, not a representation. Commented Jul 15, 2016 at 8:51
  • Could the downvoters please care to comment. Commented Jul 15, 2016 at 13:36
  • Related: stackoverflow.com/q/26713294/2943403 Commented Jul 9, 2022 at 14:28

3 Answers 3

1

There are a huge number of sorting functions in php, which can sort an array based on value or key, maintain index association and walk into child arrays.

What I think you want is the sort function, like this:

sort($array['folder1']);
sort($array['folder2']);

Or this:

foreach ($array as $key => $subarray) {
    sort($array[$key]);
}

Just keep in mind. It is not the outer array you want to sort, but its child arrays.

Sign up to request clarification or add additional context in comments.

2 Comments

Because I do not know the folder names I would need to go with the second option. If I output subarray I can see that it works. However, it does not seem to add the sorted subarray back to the original array.
Please note that I updated my answer. Just doing a sort($subarray) will only sort a copy of the child arrays. You will actually have to do a sort($array[$key]), like the updated answer instead.
1

You can use this function:

asort() - sort associative arrays in ascending order, according to the value

1 Comment

That is actualt one of the functions I tried, but it does not seem to sort it because I think it is doing the sort on folder1 and folder2.
1

use array_walk (functional way of foreach) to go through the outer array and then in there use sort

http://php.net/manual/en/function.array-walk.php
http://php.net/manual/en/function.sort.php

$arr = array(
    "folder1" => array(
        "1" => "d1_2",
        "2" => "d1_1",
        "3" => "d1_3"
    ),
    "folder2" => array(
        "1" => "d2_3",
        "2" => "d2_1",
        "3" => "d2_2"
    )
);

var_dump($arr);

array_walk($arr, function (&$e) {
    sort($e);
});

var_dump($arr);

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.