fputcsv: Empty rows in csv file after each array - php

I am trying to write a csv files with values from two arrays. Here's the code:
<?php
fopen('output.csv','w');
$merged_fields = array_combine($authors, $ids);
$range = count($merged_fields);//gives number of elements in array
$name = array_keys($merged_fields);
$id = array_values($merged_fields);
$name = str_replace(',',', ',$name);
for ($a = 0; $a <=$range; $a++) {
//filter out rows where id = '000000'
if($id[$a] == '000000'){
continue;
}
fputcsv($fp, array_filter(array($name[$a], $id[$a])));
}
}
fclose($fp);
?>
If the original array was "Smith, John" => "888888", "Smith, Jane"=>"777777" , and the next array is "Jones,John"=>"999999" there is a space after the line after each array, so in the csv the output ends up:
"Smith, John",888888
"Smith, Jane",777777
"Johnes, John",999999
I will use this csv to import data and need to get the extra lines out of there. I have tried applying "array_filter" to other parts of the array as it appears there is an empty element in there somewhere, but that hasn't worked.

The blank line is produced because you iterate one time too many over the array. You will have a few warning messages like these:
E_NOTICE : type 8 -- Undefined offset: ...
But the code will not be interrupted by that and so an empty value will be output by fputcsv, resulting in the empty line. If then you call the same code again to append to the generated file, the empty line will separate the two batches of output.
Fix this by replacing <= in the following line:
for ($a = 0; $a <= $range; $a++) {
so you get:
for ($a = 0; $a < $range; $a++) {
Remember that if an array has $range elements, the first element is at index 0 and the last at index $range-1, unless you have explicitly defined your array otherwise.

Related

Reading a log/csv file and store each value in an array

I have a csv file with headers in first line and its values in all limes.
Headers be like :
header1,header2,header3,....
If there are total 200 lines i will get 199 header1, header2 values.
Am trying to store all the values of each header in an array.
The code i tried,
for($i = 0; $i < count ( $logFile ); $i ++) {
$rr = explode ( ',', $logFile [$i] );
$eachline [] = $rr;
}
when doing this am getting 200 arrays for each line.
If suppose there are seven headers, i need seven arrays with 199 elements in it.
By the by, I don't need all the header values, I need only some headers, i can take them by splitting first line and taking split[2], split[5]... Now I want to store every line's 2nd element, 5th element .. in an array.
you may want this. hope it helps.
for($i = 0; $i < count ( $logFile ); $i ++) {
$rr = explode ( ',', $logFile [$i] );
foreach($rr as $key => $value)
{
$eachline[$key][] = $value;
}
}
then $eachline will save the arrays for header1, header2,

Using unset() on an array, but it keeps the value

I'm trying to remove an object from an array if one of his properties is null or empty, this is the code.
The array has been sorted using this function:
function sortArray($c1, $c2)
{
return ($c1->propertyToCheck < $c2->propertyToCheck);
}
In case it changes anything.
$myArray = array();
...
// Add values to the array here
...
usort($myArray,"sortArray");
for($i = 0; $i < count($myArray ); $i++)
{
if(empty($myArray[$i]->propertyToCheck))
{
unset($myArray[$i]);
// var_dump($myArray[$i]) returns NULL
}
}
echo json_encode($myArray);
// Returns the entire array, even with the values that shouldn't be there.
The code is inside a function but the array is created inside said function.
I'm using echo json_encode($myArray) to send the value back in AJAX, but the array sent is the entire array with every object inside it.
The count($myArray) is the "problem".
Once the unset() is "reached" there is one element less in the array and therefore the next call to count($myArray) will return n-1 of the previous iteration -> your loop doesn't get to the end of the array.
You have at least three choices (in ascending order of my preference)
a)
$maxIdx = count($myArray);
for($i = 0; $i < $maxIdx; $i++) {
b)
foreach( $myArray as $key=>$obj ) {
if(empty($obj->propertyToCheck)) {
unset($myArray[$key]);
c)
$myArray = array_filter(
$myArray,
function($e) {
return !empty($e->propertyToCheck);
}
);
(...and many more)
see also: http://docs.php.net/array_filter

PHP - compare elements from array and delete elements if used in function

I have a $test array which contains strings. I also have two functions, replaceOverlap that merges two overlapped strings and findNested that finds if one of the two strings is a substring from the other. The code is in PHP
What I would like to do is to iterate over the $test array and take each element ($epitope) and compare it with the rest of the $epitopes in the array one at a time, as there are some more rules in the algorithm. The issue is that if I only want to print the biggest overlapped-nested string found across the rest of the $test array, and then delete from the array those string that have been merged. This is the code I have so far. Any help will be very appreciated.
$test=array(AVNIVGYSNAQGVDY,DIKYTWNVPKI,DIKYTWNVPKIA,DIKYTWNVPKIAPKSEN,GCHGSEPCIIHRGK,IDGLEVDVPGIDPNAC,IGIKDLRAFQHYDGRTI,IIHRGKPFQLEAV,IKYTWNVPKIAPKSEN,KPFQLEAVFEANQNT,LRQMRTVTPIRMQGG,NFLESLKYVEANKGAIN,PCIIHRGKPFQLEAV,PLVKGQQYDIKYTWNVP,QQYDIKYTWNVPKI,QQYDIKYTWNVPKIA,QQYDIKYTWNVPKIAP,QQYDIKYTWNVPKIAPK,QQYDIKYTWNVPKIAPKS,QQYDIKYTWNVPKIAPKSE,QQYDIKYTWNVPKIAPKSEN,QYDIKYTWNVPK,QYDIKYTWNVPKI,QYDIKYTWNVPKIAPKS,QYDIKYTWNVPKIAPKSEN,RFGISNYCQIYPPNV,SAYLAHRNQSLDLAEQELVDCAS,TAIAVIIGIKDLRAFQH,TWNVPKIAPKSENVVVT,YAYVAREQSCR,YDIKYTWNVPK,YDIKYTWNVPKI,YDIKYTWNVPKIA,YDIKYTWNVPKIAPKSEN);
$i=0;
foreach ($test as $epitope){
$str1=$epitope;
for ($j = $i; $j < count($test); ++$j) {
$str2=$test[$j];
$value1 = replaceOverlap($str1,$str2);
$value2 = replaceOverlap($str2,$str1);
$value3 = findNested($str1,$str2);
if (replaceOverlap($str1,$str2)!=false){
array_splice($test[$j]);
print $value1;echo"</br>";
}
elseif (replaceOverlap($str2,$str1)!=false){
array_splice($test[$j]);
print $value2;echo"</br>";
}
elseif (findNested($str1,$str2)!=false){
array_splice($test[$j]);
print $value3;echo"</br>";
}
}
$i=$i+1;
}

get key and value of second last element of an array

i have an array of undefined size, for example :
<?php
$array["foo"] = 86 ;
$array["bar"] = 49 ;
$array["matt"] = 96 ;
?>
i don't want to disturb array's internal pointer , but want to get a COPY of second last value of array instead.
I don't know, why you use a map, when in fact you want an ordered list instead, but
$tmp = array_values($array);
echo $tmp[count($tmp) -2];
should do it. With php5.4 this should work either
echo array_values($array)[count($array)-2];
I'm not sure what size your array is planned for, so copying all values into a separate array might not be a good idea.
The following code slices out an array of length 1 just from the second last position and sets $key and $value.
$pair = array_slice($array, -2, 1, true);
$key = key($pair);
$value = current($pair);
PS: Should probably be put into a simple separated function?!
You can do it this way.
$array["foo"] = 86 ;
$array["bar"] = 49 ;
$array["matt"] = 96 ;
$x = count($array);
foreach($array as $row)
{
if($x == 2)
{ $secondLast = $row;}
$x--;
}
echo $secondLast;
Because you are using associative array.

PHP multidimensional array

I have an array declared above the beginning of a for loop as: $array = array();.
Now, in the for loop I start inserting values into it.
At some point I make one of its index as another array as $array[$j]=array();
And insert some values like, $array[$j][$l] = id; and so on.
Now, when I use print_r ($array); inside the loop I get the expected value of the array.
But outside the loop this newly created array (2-D) is getting lost and I am getting only a 1-D array as an output.
Can someone please tell me where the problem could lie?
The following code works properly. Perhaps you are switching your variables as strager suggests.
<?php
$array = array();
for ($i = 0; $i < 10; $i+=1) {
if ($i == 5) {
$array[$i] = array('value 1', 'value 2');
} else {
$array[$i] = $i;
}
}
print_r($array);
?>

Categories