Moving an array to the end of an array - php

So I'm trying to combine $gender and $grade and then remove them from the middle of my array and put them at the end. This is what I have so far but it adds both to the end but they're still in the middle of the output file. I feel like I'm missing something simple here. Any suggestions?
<?php
$inputFile = "Student_Data.csv";
$outputFile = "test.csv";
$count = 0;
$out = fopen($outputFile, "w");
$in = fopen($inputFile, "r");
while ($row = fgetcsv($in)) {
$gender = array($row[6]);
$grade = array($row[7]);
$merge = array_merge ($gender, $grade);
$final = array_merge ($row, $merge);
$sisline = implode(",", $final) . "\r\n";
print_r ($sisline);
$count++;
}
fclose($out);
fclose($in);
?>

Once you extract the value, remove them from the soruce.
$gender = array($row[6]);
$grade = array($row[7]);
unset($row[6],$row[7]);
or to get fancy as single line solution.
$row = array_diff_key($row,array_flip(array(6,7))) + $row;

Because the two keys you want are consecutive, you can select them and remove them in one step with array_splice
$genderAndGrade = array_splice($row, 6, 2);
$final = array_merge($row, $genderAndGrade);

Related

Weird characters jump out of arrays when used with get file contents

Hi this is a portion of my code which when ever output, the array $data2[0] seems to always output weird characters. It doesn't happens in $data2[1] or $data[2]..??? I been trying to figure this out for 2 days.
<?php
$filename = "../file/attendance_log/1414001189.txt";
$contents = file_get_contents($filename);
$contents = str_replace("\"","",$contents);
$lines = explode("\n", $contents);
$numrows = count($lines);
$x = 0;
for ($numrows; $x < $numrows; $x++)
{
echo $data2[0];
$data2 = explode(",", $lines[$x]);
echo $time = mktime(0,0,1,$data2[1],$data2[0],$data2[2]);
$user_no = $data2[3];
$item_no = $data2[4];
$quantity = $data2[5];
$waste = $data2[6];
$job_no = $data2[7];
}
?>
You're trying to explode and use the first line which has the column names in it
i slightly rewrote what you had to accomodate that and also not use a counter and
setting the default timezone too so you get what i think you were looking for
<?php
$filename = "../file/attendance_log/1414001189.txt";
$contents = file_get_contents($filename);
$contents = str_replace("\"","",$contents);
$lines = explode("\n", $contents);
date_default_timezone_set('UTC');
if (count($lines)){
$lines = array_slice($lines, 1);
foreach ($lines as $line){
$data2 = explode(",", $line);
if (count($data2) == 8){
echo $data2[0];
$time = mktime(0,0,1,$data2[1],$data2[0],$data2[2]);
echo $time . '<br>';
$user_no = $data2[3];
$item_no = $data2[4];
$quantity = $data2[5];
$waste = $data2[6];
$job_no = $data2[7];
}
}
}
?>
I had found the answer. It is because when the user save the file. It saved as Unicode UTF. It should save as Unicode UTF-8, that way there won't be any problems.

PHP - str_replace not working

I am trying to remove a list of words, which I have contained in a .txt, from a file. To do this I am reading both files using file_get_contents into strings and using str_replace.
$names = file_get_contents("countries.txt");
$map = file_get_contents("C:\\xampp\\htdocs\\www\\jvectormap\\map\\worldmap.js");
$array = explode("\n", $names);
foreach($array as $val){
$split = explode(" ", $val);
$max = count($split);
$country = "";
for($x = 1; $x < $max; $x++){
$country = $country . $split[$x];
if($x < ($max-1)){
$country = $country . " ";
}
}
$map = str_replace($country, "", $map);
}
echo $map;
The "countries.txt" contains the countries in this format:
AD Andorra
BE Belize
etc.
..which is why I am using explode() to strip the country tag.
When I echo $map the string contains all the countries even thought str_replace hasn't thrown an error. I have tried printing out $country to confirm it's reading the countries correctly along with reading it into an array and then looping through the array, using str_replace.
I think you need some modification in code
change below line
$array = explode("\n", $names);
to with these
$names = nl2br($names);
$array = explode("<br />", $names);
As you are working on window which uses \r\n for new line.
Cannot reproduce.
<?php
/* Instead of loading countries.txt */
$names = "AD Andorra
BE Belize";
$array = explode("\n", $names);
/* Instead of loading map */
$map = "Andorra Belize";
$array = explode("\n", $names);
foreach($array as $val){
$split = explode(" ", $val);
$max = count($split);
$country = "";
for($x = 1; $x < $max; $x++){
$country = $country . $split[$x];
if($x < ($max-1)){
$country = $country . " ";
}
}
$map = str_replace($country, "", $map);
}
var_dump($map);
Output:
string(1) " "
The space is expected, if you want to get rid of it use trim(). However, the replacement is working fine, if it still doesn't work your text files might be the problem.

How to Format CSV to ARRAY?

Can someone show me how to easily format an array with values like this?
I have a CSV file with values like below:
27383,15.99
80448,19.99
132876,11.99
150438,120
This is the format I would like:
$array[0]['id'] = 27838
$array[0]['price'] = 15.99
$array[1]['id'] = 80448
$array[2]['price'] = 19.99
What I have now is:
$data = file_get_contents('id_and_price.csv');
$data = explode(',', $data);
print_r($data);
//foreach($data as $d) {
// echo $d;
//}
You can do this quite easily with fgetcsv():
$arr = array();
$header = array('id', 'price');
$file = fopen('id_and_price.csv', 'r');
while($item = fgetcsv($file))
{
$arr[] = array_combine($header, $item);
}
print_r($arr);
<?php
$f = fopen('filename', 'r');
$arr = array();
while ($l = fgetcsv($f)) {
$arr[] = array_combine(array('id', 'price'), $l);
}
var_dump($arr);
?>
you need to use php explode...
http://php.net/manual/en/function.explode.php
$csv = "piece1,piece2,piece3,piece4,piece5,piece6";
$array = explode(",", $csv);
echo $array[0]; // piece1
echo $array[1]; // piece2

invalid argument when imploding in php

Im getting invalid argument error when running the following code. Im trying to change the value of a line in the $info array, then implode it, implode its parent array, and then save the whole shebang back to whence it came.
$rowpre = $_GET['row'];
$newfieldvalue = $_GET['nfv'];
$row = --$rowpre;
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
foreach ( $csvpre AS $key => $value){
$i++;
if($i = $row){
$info = explode("%%", $value);
$info[$target] = $newfieldvalue;
$presave = implode("%%", $info);
}
}
$save = implode("###", $presave);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
update below
$rowpre = $_GET['row'];
$newfieldvalue = $_GET['nfv'];
$target = $_GET['target'];
$row = --$rowpre;
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
foreach ( $csvpre AS $key => $value){
$i++;
if($i == $row){
$info = explode("%%", $value);
$info[$target] = $newfieldvalue;
$csvpre[$key] = implode("%%", $info);
}
}
$save = implode("###", $csvpre);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
Target is the field within the selected Row that i wish to update with the newfieldvalue data.
$save = implode("###", $presave);
At that point, $presave is a string, and should be an array to work with implode. Create an array where you push the $presave-values, and implode that one.
$presave contains the last processed line (i.e. a string) and implode expects an array. To store the line back in the original array, change:
$presave = implode("%%", $info);
to:
$csvpre[$key] = implode("%%", $info);
And to convert the whole CSV array into a string, change:
$save = implode("###", $presave);
to:
$save = implode("###", $csvpre);
And one more problem:
if($i = $row){
should be:
if($i == $row){
because you want to compare the variables, not assign $i.

Stacking a variable in reverse in PHP

I have a loop spitting out values and are put into a string:
$all_values = "";
while loop {
$value = "...";
$all_values .= $value . ",";
}
Output: 1,3,8,2,10...
What's the simplest way to output the same thing but numbers in reverse so the above example would come out like ...10,2,8,3,1
Put everything into an array and then join it together, reversed:
$all_values = array();
while loop {
$value = "...";
$all_values[] = $value;
}
$all_values = implode(',', array_reverse($all_values));
This is also more efficient if there are millions of values.
Add after your code:
$ar = explode(',', $all_values);
$revAr = array_reverse($ar);
$all_values = implode(',', $revAr);

Categories