Reputation: 27849
PHP's array is very flexible and useful. I counted over 30 array functions on the PHP.net array reference page. Some of them can solve my problem, but I'm looking for the best, most elegant way.
I have 2 arrays, called labor
and cost
, each containing a table:
labor = array(
0 => array('date' => date, 'labor'=> labor),
1 => array('date' => date, 'labor'=> labor),
...
);
cost = array(
0 => array('date' => date, 'cost'=> cost),
1 => array('date' => date, 'cost'=> cost),
...
);
My problem is that sometimes the number of dates don't match (i.e., there are days when you've incurred costs, even though you spent nothing on labor, or days when you had labor but no cost) - that means there are more lines in one array then the next - no way to know which has without using count()
.
What I'm interested in are only the days that had both labor and cost and I want to end up with an array:
laborcost = array(
0 => array('date' => date, 'labor'=> labor, 'cost' => cost),
1 => array('date' => date, 'labor'=> labor, 'cost' => cost),
...
)
I thought about using array_intersect()
or one of the 'u' functions, but ended totally mixed up. Before giving up and writing my own array scanning function, I wanted to see if there are any ideas that will solve my issue with 1, possibly 2, lines of code.
Upvotes: 1
Views: 292
Reputation: 67735
There's is no intersect function accepting a user-defined comparison function that allows you to modify the arrays. The simplest way is just to do it yourself.
Here are a few examples:
O(2n + m)
// Remap dates as keys for faster lookups
$result = $nlabor = $ncost = array();
foreach ($labor as $l) $nlabor[$l['date']] = $l;
foreach ($cost as $c) $ncost[$c['date']] = $c;
// Compare
foreach ($nlabor as $date => $l) {
if (array_key_exists($date, $ncost)) {
$result[] = array_merge($l, $ncost[$date]);
}
}
~O(n * m)
// Just compare them all
$result = array();
foreach ($labor as $l) {
foreach ($cost as $c) {
if ($l['date'] == $c['date']) {
$result[] = array_merge($l, $c);
break;
}
}
}
Which way is the best depends on how many elements you have in each array. When used on smaller arrays ~O(n * m) is fine, while on bigger arrays O(2n + m) will be more efficient.
Upvotes: 2
Reputation: 1241
This should do that trick. Not quite as simple as a single function.
$merge = array();
for ($i = 0; $i < count($labor); $i++) {
array_push($merge, array_merge($labor[$i],$cost[$i]));
}
Upvotes: 0