Merge and transpose 3 arrays of data [duplicate] - php

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
foreach with three variables add
(4 answers)
Closed 6 months ago.
There are three single dimensional arrays that needs to be saved in csv
$arr1=array(1,2,3);
$arr2=array('a','b','c');
$arr3=array('x','y','z');
I need to save the above arrays in the csv like the following example-
1,a,x
2,b,y
3,c,z
I have tried the following code but its not saving in that format
$handle = fopen('file.csv', 'w');
$data=array($arr1,$arr2,$arr3);
foreach ($data as $line) {
fputcsv($handle, $line);
}
fclose($handle);
Output
1,2,3
a,b,c
x,y,z

Transpose the data before writing to the CSV
$data = array($arr1,$arr2,$arr3);
$transposedData = call_user_func_array(
'array_map',
array_merge(
array(NULL),
$data
)
);
$handle = fopen('file.csv', 'w');
foreach ($transposedData as $line) {
fputcsv($handle, $line);
}
fclose($handle);

foreach ($arr1 as $key => $value) {
fputcsv($handle, array($value, $arr2[$key], $arr3[$key]));
}

try like below:-
$arr1=array(1,2,3);
$arr2=array('a','b','c');
$arr3=array('x','y','z');
$handle = fopen('file.csv', 'w');
for($i=0; $i<count($arr1); $i++) {
$data=array($arr1[$i],$arr2[$i],$arr3[$i]);
fputcsv($handle, $data);
}
fclose($handle);
output
1 a x
2 b y
3 c z

Try this,Just take the transpose of the array before fputcsv
<?php
$arr1=array(1,2,3);
$arr2=array('a','b','c');
$arr3=array('x','y','z');
$data=array($arr1,$arr2,$arr3);
$rows = count($data);
$cols = count($data[0]);
$ridx = 0;
$cidx = 0;
$out = array();
foreach($data as $rowidx => $row){
foreach($row as $colidx => $val){
$out[$ridx][$cidx] = $val;
$ridx++;
if($ridx >= $rows){
$cidx++;
$ridx = 0;
}
}
}
$handle = fopen('file.csv', 'w');
foreach ($out as $line) {
fputcsv($handle, $line);
}
fclose($handle);
?>
Output
1,a,x
2,b,y
3,c,z

<?php
$arr1=array(1,2,3);
$arr2=array('a','b','c');
$arr3=array('x','y','z');
$output = '';
$data=array($arr1,$arr2,$arr3);
$size=count($data[0]);
//all arrays must have the same size! and $data must contain at least one item
for ($i = 0; $i < $size; $i++) {
foreach ($data as $arr) {
$output .= $arr[$i] . ';';
}
$output .= "\n";
}
file_put_contents($output);
?>
Expected output:
1;a;x;
2;b;y;
3;c;z;

Related

How to take a value of the input given in a file into an array with specified format

Input Format is
6
4 5 1 9 8 7
Where first line gives the length of the array or the number of character
Required Output
array{4,5,1,9,8,7}
<?php
$fp = fopen("C://wamp//www//phptut////Insertion Sort//stdin.txt", "r");
$m = (int) fgets($fp);
var_dump($m);
$arr = array();
for ($i=0; $i<$m; $i++) {
fscanf($fp, "%d", $arr[$i]);
}
//var_dump($arr);
foreach($arr as $value) {
print $value;
}
?>
$fp = fopen("your file loc", "r");
fscanf($fp, "%d", $m);
$ar= fgets($fp);
$arr = explode(" ", $ar);
// here this explode and implode is done because here whatever you want to do with your array ..do it
$value = implode(" ", $arr);
print $value;

Convert csv in php and get unique value

I would like to convert a csv file that has duplicate contents and i would like to sum the quantity and extract the price without sum it.
file.csv :
code,qty,price
001,2,199
001,1,199
002,2,159
002,2,159
Actual php that sum the quantiy and get a result with unique value and total qty.
<?php
$tsvFile = new SplFileObject('file.csv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");
$file = fopen('file.csv', 'w');
$header = array('sku', 'qty');
fputcsv($file, $header, ',', '"');
foreach ($tsvFile as $line => $row) {
if ($line > 0) {
if (isset($newData[$row[0]])) {
$newData[$row[0]]+= $row[1];
} else {
$newData[$row[0]] = $row[1];
}
}
}
foreach ($newData as $key => $value) {
fputcsv($file, array($key, $value), ',', '"');
}
fclose($file);
?>
the result for this is:
code,qty
001,3
002,4
and i would like to add price, but without sum it.
The result i need is:
code,qty,price
001,3,199
002,4,159
I haven't tested this yet, but I think this is what you are looking for:
<?php
$tsvFile = new SplFileObject('file.csv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");
$file = fopen('file.csv', 'w');
$header = array('sku', 'qty');
fputcsv($file, $header, ',', '"');
foreach ($tsvFile as $line => $row) {
if ($line > 0) {
if(!isset($newData[$row[0]])) {
$newData[$row[0]] = array('qty'=>0, 'price'=>$row[2]);
}
$newData[$row[0]]['qty'] += $row[1];
}
}
foreach ($newData as $key => $arr) {
fputcsv($file, array($key, $arr['qty'], $arr['price']), ',', '"');
}
fclose($file);
?>
To start with, there's a nice function on the PHP page str_getcsv which will help you end up with a more legible array to work with:
function csv_to_array($filename='', $delimiter=',') {
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
This is purely for legibility sake but now comes the code which would allow you to work over the array.
$aryInput = csv_to_array('file.csv', ',');
$aryTemp = array();
foreach($aryInput as $aryRow) {
if(isset($aryTemp[$aryRow['code'])) {
$aryTemp[$aryRow['code']['qty'] += $aryRow['qty'];
} else {
$aryTemp[$aryRow['code']] = $aryRow;
}
}
In the above code, it simply:
Loops through the input
Checks whether the key exists in a temporary array
If it does, it just adds the new quantity
If it doesn't, it adds the entire row
Now you can write out your expectant csv file :)

echoing foreach loop

i have the following code
$contents = file_get_contents('folder/itemtitle.txt');
$fnamedata = file_get_contents('folder/fname.txt');
$fnamearray = explode("\n", $fnamedata);
$contents = explode("\n", $contents);
foreach ($contents as $key => $itemline)
{
}
foreach ($fnamearray as $key2 => $fname)
{
echo ($fname);
echo ($itemline);
}
what i want to do is to have the first line of each file echo so the output looks like
fname[0},itemline[0],fname[1],itemline[1]
what i am getting with the following is just this
fname[0],fname[1],fname[2].... ect
h
Assuming the indexes will always match:
$contents = file_get_contents('folder/itemtitle.txt');
$fnamedata = file_get_contents('/home/b1396hos/public_html/ofwgkta.co.uk/dd_folder/fname.txt');
$fnamearray = explode("\n", $fnamedata);
$contents = explode("\n", $contents);
for($i = 0; $i < count($contents); $i++)
{
echo $fnamearray[$i];
echo $contents[$i];
}
Since both arrays are simple, consecutive numeric indexed arrays, you can just use a for loop:
$l = max(count($fnamedata),count($contents));
for($i=0; $i<$l; $i++) {
$itemline = $contents[$i];
$fname = $fnamearray[$i];
// do stuff
}

How to convert CSV to JSON with requires one line in CSV file will export one file JSON

I have a problem and need a help from you!
I want to convert CSV to JSON,and 1 line in CSV with export 1 file JSON (JSON's content is CSV line's content,and JSON's name is id of this line).
I try to do,but it's only display and download JSON.
Please give me a suggestion for this problem.
Thanks for your help!
<?php
header('Content-type: application/json');
$feed = 'jsondata_palpad.csv';
$keys = array();
$newArray = array();
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $arr;
}
$data = csvToArray($feed, ',');
$count = count($data) - 1;
$labels = array_shift($data);
foreach ($labels as $label) {
$keys[] = $label;
}
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
header("Content-type: application/json");
header("Content-Disposition: attachment; filename=test.json");
header("Expires: 0");
header("Pragma: no-cache");
echo json_encode($newArray);
?>
So you have a titled CSV file.
To read it, first convert the rows into an array:
$csv = array_map("str_getcsv", file($filename));
$head = array_shift($csv);
For conversion into an associative array:
$csv = array_map("array_combine", array_fill(0, count($csv), $head), $csv);
To generate the files:
foreach ($csv as $index => $row) {
file_put_contents("$index.json", json_encode($row));
}
Here the loop counter $index is used for generating the filenames.
See the manual for explanations on:
array_map
str_getcsv
file_put_contents
If you did want something else, write a more precise question next time.

PHP + XPath + fputcsv - Storing data in arrays

I'm parsing some HTML with DOM/Xpath, with the ultimate goal of generating a .CSV file with the data I've grabbed with my queries.
The current code below works, but only returns the last product name. I know I'm sort of on the right track here, but I'm maxed out and cannot figure this out. Any help would be greatly, greatly appreciated. Thanks.
$names = array();
$result = $xpath->query("//div[#class='product-name']");
foreach ($result as $nam) {
$names[] = $nam->nodeValue;
$i = 0;
$values=$names[$i] = $nam->nodeValue;
}
$list = array (
array('Product Name','Stock Level','Price'),
array($values, '456', '789'),
);
$fp = fopen('product-sheet.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
I'm not entirely sure what you're trying to achieve but hopefully this will get you nearer to your goal.
<?php
//mocked up input, substitute for your HTML source
$input = "<html>
<div class='product-name'>test1</div>
<div class='product-name'>test2</div>
<div class='product-name'>test3</div>
<div class='product-name'>test4</div>
<div class='product-name'>test5</div>
</html>";
$doc = new DOMDocument();
#$doc->loadHTML($input);
libxml_use_internal_errors(FALSE);
$xpath = new DomXPath($doc);
$list = array (
array('Product Name','Stock Level','Price')
);
$result = $xpath->query("//div[#class='product-name']");
foreach ($result as $nam) {
$value = $nam->nodeValue;
$list[] = array($value, '456', '789'); //Appends an array to the lists array
}
$fp = fopen('product-sheet.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
The problem is you're setting $i inside your loop.
foreach ($result as $nam) {
$names[] = $nam->nodeValue;
$i = 0;
$values=$names[$i] = $nam->nodeValue;
}
On each iteration, $i is being reset to 0. Try something like this instead:
for($i=0; $i< count($result); $i++) {
$names[] = $result->nodeValue;
$values=$names[$i] = $result->nodeValue;
}

Categories