Transposing csv values in php - php

I need to transpose some values in some csv files that we get sent on a regular basis so that they are able to be imported into a website and I'm not sure the best way to go about doing it.
The data arrives in a csv file with a header row containing the column names, and the first column values are product ID's. The data looks like this…
ID F F-VF VF VF-XF XF
1 840 960 1080 1248 1944
2 1137.5 1300 1462.5 1690 2632.5
3 1225 1400 1575 1820 2835
What I'm looking to do is change this around so the column name and it's value are put into a new line for each value for the same id like so…
ID COND VALUE
1 F 840
1 F-VF 960
1 VF 1080
1 VF-XF 1248
1 XF 1944
2 F 1137.5
2 F-VF 1300
2 VF 1462.5
2 VF-XF 1690
2 XF 2835
I may also need to add some strings into the cells - is that easy to do?
Thanks a lot

Not necessarily the most elegant version, just to get an idea.
Something like this would work in case it's a existing csv, which gets read and overwritten with the transposed version.
// assuming a dataset like
// ----
// fruit, apple, pear, peach
// animal, eagle, bear, wolf
// car, renault, fiat, nio
$f = fopen($savePath, 'r');
$header = [];
$data = [];
while($row = fgetcsv($f, 0, ",")) {
$header[]=$row[0];
for ($i = 1; $i < sizeof(array_keys($row)); $i++) {
$data[$i][$row[0]]=$row[$i];
}
}
fclose($f);
$f = fopen($savePath, 'w');
fputcsv($f, $header);
foreach ($data as $recordColDataSet) {
fputcsv($f, array_values($recordColDataSet));
}
fclose($f);
Transposing arrays could also be something to look at eg in this question here:
Transposing multidimensional arrays in PHP

Have you tried any of the standard PHP methods like: str_getcsv() or fgetcsv()?
A quick search of "php csv" provides a TON of possible solutions. I suggest trying a few, then reporting back here if you have a specific problem.

Related

echo each wordin file get contents

Hello I have a text which written like this:
sh222022 HALIMA 20220329 1200 -21.4 82.5 S TS 45 994
wp932022 INVEST 20220329 1200 11.1 115.7 W DB 20 1008
I try separate word each but it didnt work
<?php
// get files content
$file_investraw = file_get_contents("./cache/data.txt", FILE_IGNORE_NEW_LINES);
// put the data into arrays
$data_investraw = explode("\n", $file_investraw);
?>
I want the output like this, so how should I echo each word I like?:
sh222022
HALIMA
20220329
1200
-21.4
82.5
S
TS
45
994
or if I want to echo each word or each value, I cant separate it. Thank You
you can do that like this.
// get files content
$file_investraw = file_get_contents("./cache/data.txt", FILE_IGNORE_NEW_LINES);
// put the data into arrays and remove the empty element from array
$data_investraw = array_filter(explode("\n", $file_data));
// make the array filter data into string
$data_investraw = implode(' ',$data_investraw);
// explode the string into array
$data_investraw = array_filter(explode(" ", $data_investraw));
this way you can achieve your desired output.

Splitting a list of strings into new lists of similar length

Say I have a list of 65 strings.
I need to split this single list into multiple "pools" that have a similar amount of strings.
The amount cannot be over 32.
In this list of 65, they're all ranked from 1st to 65th.
For a list of 65 strings, it'd split into one pool of 21, and two pools of 22.
For a list of 34 strings, it'd split into one pool of 18, and one pool of 18.
For a list of 115 strings, it'd split into one pool of 28, and three pools of 29.
And so on.
However, the new lists need to be fairly ranked.
In example it should be like so:
rank 1 in pool 1
rank 2 in pool 2
rank 3 in pool 3
rank 4 in pool 1
rank 5 in pool 2
rank 6 in pool 3
This way, rank 1 and rank 4, become rank 1 and 2 in their new list.
Same goes for the rest.
I'm thinking I'd need to use array_chunk in combination with a modulo operation, but I can't seem to wrap my head around it.
This is not as difficult as it might seem:
// settings
$cellCount = 115;
$maxPoolSize = 32;
// create test array with numbered strings
$testArray = array_fill(1,$cellCount,'Cell ');
foreach ($testArray as $key => $value) $testArray[$key] .= $key;
// determine the number of pools needed
$arraySize = count($testArray);
$poolCount = ceil($arraySize/$maxPoolSize);
// fill the pools
$poolNo = 0;
foreach ($testArray as $cell)
{
$poolArray[$poolNo][] = $cell;
$poolNo++;
if ($poolNo == $poolCount) $poolNo = 0;
}
// show result
echo '<pre>';
print_r($poolArray);
echo '</pre>';
I'm sure there are other solutions, but this seems to do the job.
I think you're on the right way, by using array_chunk and a modulo operation, that's the way i would choose.
It would be like:
$countarray = count($myarray);
$modulo = 2;
while ($countarray>32)
{
$result = $countarray/$modulo;
if($result>32)
$modulo++;
}
$newpool = array_chunk($myarray, $modulo);
I'm not a god in php, so i hope it will help ! Sorry for my poor english.

Reading content from positional text file in PHP?

I have text file having the following format
00151422 N8X 3V6 2013-11-11 00:19:00.000 IN patricksoong#hotmail.com E 200-2462 Howard Avenue Windsor ON CAN N8X3V6 M Dr. Patrick Soong
00331448 T6E 2R1 2010-03-01 00:00:00.000 IN atirlea#yahoo.com E 9743 88 Ave NW Edmonton AB CAN T6E2R1 Alina Tirlea Engstrom
00364578 K7N 1A3 2011-01-12 00:00:00.000 IN E 4463 Bath Rd Amherstview ON CAN K7N1A3 M Mr. Martin Kandler
The above positional text file contains 3 records and 20 fields in each record. Also I now the size for each column. How will i read records and fields with in a record using PHP?
Size of fields are
f1=8;f2=10;f3=10;f4=10;f5=255;f6=50;f7=255;f8=10;f9=10;f10=50;f11=50;f12=1;f13=20;f14=50;f15=50;f16=60;f17=10;f18=20;f19=20;f20=1;
Use a substr() inside some kind of loop. Untested, but should give you an idea:
$lengths = [8,10,10]; // define all the lengths
function fixed_width_data_to_array($data, $lengths) {
foreach($rows as $row) {
$position = 0; // start at the beginning of the row
foreach($lengths as $length) {
// add current field to array
$my_data[] = trim(substr($row, $position, $length));
// move the 'pointer' to the start of the next field
$position += $length;
}
// add current row to an array
$my_array[] = $my_data;
}
return $my_array;
}

PHP - Convert a messy string to a useable one

I have a bunch of data from a football team that needs tidying up. Currently, it looks like this (for demonstration purposes, I've only included 3):
1
Team One
9 7 1 1 31 13 18 22
2
Team Two
9 6 2 1 25 21 4 19
3
Team Three
9 4 3 2 26 18 8 14
For clarity, I'll deconstruct the first 3 lines:
1\t\n
Team One\n
9\t7\t1\t1\t31\t13\t18\t22
Notice how there is a tab and then a linebreak after the position of each team. Then, the team name on the next line, with just a linebreak. And then finally, all of the details about that team. Then the next team's stats start.
I need it to be converted to:
1,Team One,9,7,1,1,31,13,18,22
2,Team Two,9,6,2,1,25,21,4,19
3,Team Three,9,4,3,2,26,18,8,14
Each line starts with the team's position, then team name, then each stat -- all separated by commas.
I've attempted doing this with very little luck. I imagine some kind of fancy regex can do the trick, but I wouldn't know how... hopefully someone can help!
You can use
$in = file("log.txt");
$out = fopen("php://output", "w");
foreach(array_chunk($in, 3) as $group) {
$group = array_map("trim", $group);
$group[2] = implode(",", str_getcsv($group[2], "\t"));
fputcsv($out, $group);
}
Output
1,"Team One","9,7,1,1,31,13,18,22"
2,"Team Two","9,6,2,1,25,21,4,19"
3,"Team Three","9,4,3,2,26,18,8,14"
If you want empty enclosure then use
fputcsv($out, $group, ",", " ");
Output
1, Team One , 9,7,1,1,31,13,18,22
2, Team Two , 9,6,2,1,25,21,4,19
3, Team Three , 9,4,3,2,26,18,8,14
<?php
$resultstr = array();
foreach($Teams as $items){
$resultstr[] = $items['Team One'];
}
$items = implode(", ",$resultstr);
echo $items;
?>
something like that. You can edit it with your own data because you did not mention that in your question.

I'm creating a random array in PHP and my code doesnt seem to output a truly random answer

I want to construct an array of 3 offers that output in a random order. I have the following code and whilst it does output 3 random offers it doesn't appear to be random. The first value in the generated array always seems to be from the 1st 2 records in my offers table. The offers table only has 5 records in it (I dont know if this is affecting things).
$arrayOfferCount = $offerCount-1;
$displayThisManyOffers = 3;
$range = range(0, $arrayOfferCount);
$vals = array_rand($range, $displayThisManyOffers);`
Any help or advice would be appreciated.
Working fine here. Benchmark it over lots of runs instead of just gut feeling... here it is for 1,000 tries:
<?php
$offerCount = 5;
$arrayOfferCount = $offerCount-1;
$displayThisManyOffers = 3;
$range = range(0, $arrayOfferCount);
for($i = 0; $i < 1000; $i++) {
$vals = array_rand($range, $displayThisManyOffers);
foreach($vals as $val) {
$counts[$val]++;
}
}
sort($counts);
print_r($counts);
Generates:
Array
(
[0] => 583
[1] => 591
[2] => 591
[3] => 610
[4] => 625
)
I know that mt_rand() is much better PRNG.
However, in your case you need to let the database select them for you
SELECT * FROM ads ORDER BY RAND() LIMIT 0, 3
It is probably randomly picking which to display, but displaying them in the same order they appear in your array. If you do it enough times (~20) you should get the third one to show up once if this is the case (chances of choosing exactly the last 3 out of 5 would be 1 in 5*4, so around every 20th one you'll see the third option appear).
array_rand seems not to work properly sometimes (see PHP-Manual comments).
Workaround: Get the array size and pick a random index using the function mt_rand

Categories