This is kind of a fun problem, so here's something that would probably work for you, out of the box :)
First, define your items:
$items = array(
array(
"time" => "090019",
"val" => "2.444",
"qta" => "292",
"dir" => "up",
"param" => "S",
),
array(
"time" => "090019",
"val" => "2.442",
"qta" => "938",
"dir" => "dwn",
"param" => "N",
),
array(
"time" => "090019",
"val" => "2.442",
"qta" => "220",
"dir" => "up",
"param" => "N",
),
array(
"time" => "100043",
"val" => "2.44",
"qta" => "220",
"dir" => "dwn",
"param" => "N",
),
);
Next, iterate through the items array once to group items together based on the same time and val:
$grouped_items = array();
foreach($items as $item) {
$key = "{$item['time']}-{$item['val']}";
if( empty($grouped_items[$key]) ) $group_items[$key] = array();
$grouped_items[$key][] = $item;
}
At this point, you have an array with keys equal to time-val. Each of those is a subarray containing a list of all items matching that item-val (so you grouped together the same time/val items). Finally, you can create your merged list:
$final_items = array();
foreach($grouped_items as $item_list) {
$final_items[] = mergeItems($item_list);
}
// merge a list of items with the same time and val
function mergeItems($items) {
$merged_item = array(
"time" => $items[0]['time'],
"val" => $items[0]['val'],
"qta" => 0,
"dir" => null,
"param" => $items[0]['param'],
);
// add or subtract qta values
foreach($items as $item) {
if( $item['dir'] == "up" ) {
$merged_item["qta"] += (int) $item["qta"];
}
else {
$merged_item["qta"] -= (int) $item["qta"];
}
}
// set the final qta and dir value
if( $merged_item["qta"] < 0 ) {
$merged_item["qta"] *= -1;
$merged_item["dir"] = "down";
}
else {
$merged_item["dir"] = "up";
}
return $merged_item;
}
Now $final_items has your merged list.
If you paste all of this into one PHP script, it'll run and give you the output you want. If it doesn't do exactly what you want with your real data, then you forgot to mention something in your question and can probably use this example to create something that will work :)