0

I only found questions on how to sort arrays with subarray values, but I would like to know if you can sort a subarray with subarray values.

foreach ($el->getArray('plain') as $element){

   foreach ($element as $data)
   {
      <?php echo $data['name']; ?>
      <?php echo $data['value']; ?>
   }
}

I think the best solution is to instantiate $array by doing:

$array = $el->getArray('plain');

before the foreach and then sort it immediately and then loop through it.

However, I am not sure you can sort an array inside an array. First, is this possible and second how would you do it?

3
  • 1
    Third: can you provide actual array / desired array examples? (Yes, it is possible sort sub-arrays) Commented Mar 9, 2016 at 18:51
  • 2
    you're overthinking it. php doesn't care if an array is nested 100 levels deep. an array's an array, and can be sorted with all of the various sort-type functions. how you pass that array to the sort function matters, but once it's inside the sort function, it's an array like any other. Commented Mar 9, 2016 at 18:52
  • Ah, ok thanks. I thought it could cause some side effects. Commented Mar 9, 2016 at 18:54

1 Answer 1

1

As per my comment above, stop overthinking:

php > $arr = array(array('c', 'b', 'a'), array('r', 'q','p'));
php > var_dump($arr);
array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(1) "c"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "a"
  }
  [1]=>
  array(3) {
    [0]=>
    string(1) "r"
    [1]=>
    string(1) "q"
    [2]=>
    string(1) "p"
  }
}
php > sort($arr[1]);
php > var_dump($arr);
array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(1) "c"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "a"
  }
  [1]=>
  array(3) {
    [0]=>
    string(1) "p"
    [1]=>
    string(1) "q"
    [2]=>
    string(1) "r"
  }
}

Note how the r/q/p array has now become p/q/r - it's been sorted, even though it's an array nested in another array.

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

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.