Sorting a multidimensional array based on an ordered array

This is perhaps the oldest question in the book with hundreds of resources available, but so far every solution I tried has not solved my problem. I hope you can help.

I am trying to display a graph showing the last 31 days of data. The resulting array is as follows:

$data[ 0 => 'day' => 10, 'amount' => 5, 'count' => 2 1 => 'day' => 16, 'amount' => 4, 'count' => 2 2 => 'day' => 21, 'amount' => 16, 'count' => 1 3 => 'day' => 11, 'amount' => 0, 'count' => 0 4 => 'day' => 12, 'amount' => 0, 'count' => 0 ] 

Essentially, this array consists of two parts. The first 3 internal arrays are days that contain sums and calculations, the remaining 27 are unaccounted for several days with their number and number of samples set to 0. So for example, $data[5] will be day 13 and $data[21] day 31. $data[22] will then be equal to the 1st day, which will continue until 9 days, thus showing the last 31 days.

In addition, there is an ordered array of days that we want to print.

 $days[ 0 => 'day' => 10 1 => 'day' => 11 2 => 'day' => 12 ... 30 => 'day' => 9 ] 

I tried the following, but as long as $data now streamlined, it is essentially just a replica of $days and loses other values ​​stored in $data .

 $data = array_uintersect($days, $data, array($this, 'compare_days')); function compare_days($order, $array) { return strcmp($order['day'], $array['day']); } 

What? How can I sort $data so that it saves data and orders them as desired in $days ?

+4
source share
2 answers

Just use uasort as

 uasort($data, function($a,$b) use ($days){ foreach($days as $value){ if($a['day'] == $value['day']){ return 0; break; } if($b['day'] == $value['day']){ return 1; break; } } }); 

Demo

+3
source

You can use this:

 foreach ($data as $key => $row) { $days[$key] = $row['day']; $amount[$key] = $row['amount']; } array_multisort($days, SORT_ASC, $amount, SORT_ASC, $data); print_r($data); 
0
source

All Articles