skip to Main Content

I´m trying to sort the last dimension of the following array

$inventory = array(
    "author" => array(
        "1" => "Evans, Dave",
        "2" => "Burnett, Bill",
    ),
    "title" => array(
        "1" => "Designing your life",
    ),
    "subject" => array(
        "1" => "Vocational guidance",
        "2" => "Decision making",
        "3" => "Self-realization",
    )
);

The desired output would be something like this:

author  Burnett, Bill
author  Evans, Dave
title   Designing your life
subject Decision making
subject Self-realization
subject Vocational guidance

There are a bunch of sorting examples that doesn’t work. Any ideas? Please don’t answer without testing.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks RJK (and Rob Eyre) for this usefull answer. I have come to this solution, using asort within a for loop.

    $keys = array_keys($inventory);
    for ($i = 0; $i < count($inventory); $i++) {
        asort($inventory[$keys[$i]]); 
        foreach($inventory[$keys[$i]] as $key => $value) {
            echo $keys[$i]."&emsp;".$value."<br />";
        }
    }
    echo "<br />";
    

    But I think the array_walk solution is more professional. Thanks.


  2. You can do either of the following:

    1. Ignoring index association (as commented by Rob):
    array_walk($inventory, function(&$v, $k) {
        sort($v);
    });
    

    var_dump returns:

    array(3) {
      ["author"]=>
      array(2) {
        [0]=>
        string(13) "Burnett, Bill"
        [1]=>
        string(11) "Evans, Dave"
      }
      ["title"]=>
      array(1) {
        [0]=>
        string(19) "Designing your life"
      }
      ["subject"]=>
      array(3) {
        [0]=>
        string(15) "Decision making"
        [1]=>
        string(16) "Self-realization"
        [2]=>
        string(19) "Vocational guidance"
      }
    }
    
    1. Maintaining index association:
    array_walk($inventory, function(&$v, $k) {
        asort($v);
    });
    

    var_dump returns:

    array(3) {
      ["author"]=>
      array(2) {
        [2]=>
        string(13) "Burnett, Bill"
        [1]=>
        string(11) "Evans, Dave"
      }
      ["title"]=>
      array(1) {
        [1]=>
        string(19) "Designing your life"
      }
      ["subject"]=>
      array(3) {
        [2]=>
        string(15) "Decision making"
        [3]=>
        string(16) "Self-realization"
        [1]=>
        string(19) "Vocational guidance"
      }
    }
    

    Note that both of these solutions will change the type of your indexes from string to int.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search