Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging PHP Arrays

Tags:

arrays

php

I have multiple associative arrays that I want to merge if all values except startdate are the same. If two arrays are indeed the same, I want to merge them and create a new element enddate so that startdate and enddate show the date range. All dates within the range must be represented in the original arrays, i.e. if a date is missing, the dates on either side of it must not be merged.

Array('color'=>'red','size'=>'large','shape'=>'circle','startdate'=>'2011-08-17')
Array('color'=>'red','size'=>'large','shape'=>'circle','startdate'=>'2011-08-18')
Array('color'=>'red','size'=>'large','shape'=>'square','startdate'=>'2011-08-20')

should become:

Array('color'=>'red','size'=>'large','shape'=>'circle','startdate'=>'2011-08-17','enddate'=>'2011-08-18')
Array('color'=>'red','size'=>'large','shape'=>'square','startdate'=>'2011-08-20')

So far I have tried looping through each array and creating a multidimensional array:

foreach($arrays as $id => $array){
    $mergearray[$array['red']][$array['large']][$array['circle']] = $id;
};

in order to check whether another array has the same values. I'm trying to use those arrays to reconstruct arrays in the original structure.

like image 853
user774528 Avatar asked Nov 14 '22 18:11

user774528


1 Answers

Avoid the day/ date functions it's a waste of cpu time for no added benefit (answer from Dave). Avoid the massive array function use (answer from adlawson), same waste of time, just ordering arrays and processing the smart way will be much faster.

But mostly, what are you trying to do, why are those arrays like that and ... is there an SQL behind all that ?

Because if there is, there's much simpler solutions than attempting to merge badly-formed arrays (with all due respect, the transformation you seek implies that something went wrong at some point.. a start_time becoming an end_time denotes an attempt at keeping a full item history, which has no place in PHP itself imho).

I'll give you the right PHP code if it really is what you need but I have quite a doubt it's the correct way to go forward for your application.

like image 121
Morg. Avatar answered Dec 20 '22 05:12

Morg.