I have a text file I’m reading and treating line by line and I wish to put the resultant variables (post treatment) into a nested array, so for each new line of the text file a new index will be created in the array with 2 values being placed into the nested associative array – so far so good.
$arr = file('file.txt') or die('ERROR: Cannot find file');
$add_data = array(array('opc'=>$outward_pc,'lkey'=>$lkey));
$i=0;
foreach ($arr as $line) {
$outward_pc = trim(substr($line,0,4));
$lkey = trim(substr($line,15,6));
$add_data[$i]['opc'] = $outward_pc;
$add_data[$i]['lkey'] = $lkey;
$i++;
}
However, the tricky part comes when I only want to add those 2 variables to the nested array if their combined values are unique
e.g. from the variable pairs below I would only want to add 4 new indexes to the array as the combinations ‘AB10’ and ‘000002’, ‘AB10’ and ‘000004’, and ‘AB21’ and ‘000003’ both appear more than once
'AB10' and '000002'
'AB10' and '000002'
'AB10' and '000004'
'AB10' and '000004'
'AB21' and '000002'
'AB21' and '000003'
'AB21' and '000003'
I think because I’m dealing with a nested (and associative) array any form of literature on the web is proving hard to come by, particularly with regards to how to correctly write the !in_array function.
I’ve failed miserably so far to come up with anything close to the right syntax. My (admittedly poor) flailing around is shown below:
if (!in_array(array($outward_pc, $lkey), $add_data)) {
$add_data[$i]['opc'] = $outward_pc;
$add_data[$i]['lkey'] = $lkey;
}
Any help gratefully received!
Why not create a concatenation of the two values and use that as the key in your
$add_dataarray. That way duplicate values would just overwrite each other.