Merging and Sorting two arrays in PHP


Suppose we have two PHP arrays. Now if we want to merge these two array, then there is a function in PHP to do this. Just use the below code to merge two arrays in PHP.


$combinedArray = array_merge($firstArray, $secondArray);

The above code will return a new combined array of the two arrays.

Now if we want to sort this new array, then :


foreach($combinedArray AS $val) {

$dates[] = strtotime($val['date']);  // here 'date' is the key in our $firstArray and $secondArray and our new array will be sorted according to this.

}

array_multisort($dates, SORT_ASC, $combinedArray);

Note :- Both the arrays $firstArray and $secondArray must have the ‘date’ key, because the new array $combinedArray will be sorted according to this.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s