I have two arrays with elements:

First array

array( [0] => array( 'data'=> '22.06.2015', 'name'=>'qq', 'text'=>'privet 4eloveki', ), [1] => array( 'data'=> '19.06.2032', 'name'=>'qaaaq', 'text'=>'privet aaa', ), 

Second array

 array( [0] => array( 'data'=> '02.06.2012', 'name'=>'bbb', 'text'=>'poka', ), [1] => array( 'data'=> '05.01.1032', 'name'=>'qaaaq', 'text'=>'poka aaa', ), 

Task

Get one array at the output and sort the elements by the 'data' field (the most relevant ones first)

1 answer 1

First we glue the arrays, then we apply the sorting:

 $mergedArr = array_merge($arr1, $arr2); usort($mergedArr, function($arr1, $arr2){ $time1 = strtotime($arr1['data']); $time2 = strtotime($arr2['data']); if ($time1 == $time2) return 0; return ($time1 < $time2) ? -1 : 1; }); echo '<pre>'; print_r($mergedArr); echo '</pre>'; 

array_merge - Merges one or more arrays. http://php.net/manual/ru/function.array-merge.php

But note that if the keys are not numbers, i.e. I will associative arrays, the merge will not work, because

if the input arrays have the same string keys, then each subsequent value will replace the previous one

usort - usort array by value using a custom function to compare elements http://php.net/manual/ru/function.usort.php


By the way, in PHP7 usort you can write:

 usort($mergedArr, function($arr1, $arr2){ return strtotime($arr1['data']) <=> strtotime($arr2['data']); }); 
  • Did I understand correctly that there is a typo in this line? if (strToTimeFunc ($ arr1 ['data']) == strToTimeFunc ($ arr2 ['data']) return 0; -and what sense does it carry? - tsx
  • @tsx I just experimented and forgot to fix it. Now there is $time1 == $time2 - Alexey Shimansky