Ave
Ave

Reputation: 83

PHP trying to sort an array in an array

      // sort by day date keys
      ksort($unavailable);
      // sort time blocks of day by start_time
      foreach($unavailable as $each) {
        usort($each['blocks'], function($a, $b) {
          return strcmp($a->start_time, $b->start_time);
        });
      }

As you can see we are trying to sort an array by keys, then the blocks within an array by the value start_time

This is how the array looks like

[
  "2015-04-25" => [
    "blocks" => [
      $object1,
      $object2,
      $object3
    ]
  ]
]

After some debugging I realized that the problem is the modifications to blocks is not reflected in the original $unavailable array, it is not referencing the same array it seems...

For example:

foreach($unavailable as $each) {
  $each['blocks'] = null;
}

// $unavaiable[$date]['blocks'] still has original object(s)

What is the solution?

Upvotes: 0

Views: 44

Answers (2)

roullie
roullie

Reputation: 2820

Reference it to the parent

foreach($unavailable as $key => $each) {
    usort($unavailable[$key]['blocks'], function($a, $b) {
      return strcmp($a->start_time, $b->start_time);
    });
  }

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

Solution is:

foreach ($unavailable as &$each) // see that & here?

Adding & to $each means that all changes made to $each will be applied to elements of $unavailable.

Upvotes: 1

Related Questions