How to create custom CSV files using PHP? - php

In the $csv_array_attributes[0] represents every column for my csv file. sku is the product id. In $csv_array_attributes[0] represents all of the product ids for my csv(which is the rows value form column sku). In the query below I extract all of the products ids, attributes names and attributes values. My problem is that I have to compute my $csv array in order to assign for each attribute name(columns) the attribute values. In $final_string somehow I want to memorize all of the attributes values for a products (see the commented part). Thx in advance for the help. Im really stuck with this :(
$csv_array_attributes[0] = "sku%%".$header;
//GETTING ATTRIBUTES VALUES
$i = 1;
foreach($xml->children() as $content){
$id_produs = $content->ProductCode;
$csv_array_attributes[$i] = $id_produs;
$i++;
}
$select = mysql_query("SELECT id_prod.id_produs, GROUP_CONCAT('^^',nume_attr) AS nume_at, GROUP_CONCAT('^^',val_attr) AS val_at FROM attributes
INNER JOIN id_prod
ON id_prod.id_id_produs = attributes.id_produs
GROUP BY id_prod.id_produs");
$i = 0; $id_prod = array();
while ($row = mysql_fetch_array($select)){
$id_produs = $row['id_produs'];
$nume_attr = explode(",^^",substr($row['nume_at'],2));
$val_attr = explode(",^^",substr($row['val_attr'],2));
$id_prod[$id_produs] = $nume_attr;
$i++;
}
// var_dump(count($id_prod));
$nume = explode("%%", $csv_array_attributes[0]);
$csv[0] = $csv_array_attributes[0];
$i = 1;
foreach ($id_prod as $key => $value) {
// comment part
//$final_string = "";
//if (attr_name has attribute_value for product i ){
// $final_string.= attribute_value."%%";
//}else{
// $final_string.= "%%";
//}
//end comment part
$csv[$i] = $csv_array_attributes[$i]."%%".$final_string;
$i++;
}
//var_dump($csv_array_attributes[0])
//CREARE CSV
$file = fopen("attributes.csv","w+");
foreach ($csv as $line){
fputcsv($file,explode('%%',$line),"^","`");
}
To see the current result please click HERE

Actually I only can give you a hint how I would create a array for csv.
// header
$csv[0][0] = "one";
$csv[0][1] = "two";
$csv[0][2] = "three";
$csv[0][3] = "four";
$csv[0][4] = "five";
// body
$csv[1][0] = "some";
$csv[1][1] = "values";
$csv[1][2] = "that";
$csv[1][3] = "could";
$csv[1][4] = "be";
$csv[2][0] = "here";
$csv[2][1] = "in";
$csv[2][2] = "this";
$csv[2][3] = "little";
$csv[2][4] = "array";
This is only a sample to view the array setup.
If you have set up the header, lets say by a for you can fill the 2 demensional array.
If this is set up you can use a foreach to build your CSV
Sample
$seperator = ";";
$ln = "\r\n";
$csv_output = "";
foreach($csv as $c){
foreach($c as $value){
$csv_output .= $value . $seperator;
}
$csv_output . $ln;
}
csv output
one;two;three;four;five;
some;values;that;could;be;
here;in;this;little;array;
a row;with an;;empty;field;
empty fields are no problem since you seperate them all with a ;

Related

How to extract data from bracket and replace in laravel

My string is
"invoice = [[invoice_no]]
customer = [[customer]]
item = [[item]]"
How can i do upper string to covert the following with php?
"invoice = " $data->invoice_no
"customer = " $data->customer
"item = " $data->item
I already created one function for same type of parsing, it replaces {{item}} by give data like $data['item']. here is example , you can change according to your requirement.
<?php
function putValuesInHTML($html_form,$reportData){
preg_match_all('/{{([A-Za-z0-9_ ]+?)}}/', $html_form, $fields);
$arrInHtml = array();
$valsForHtml = array();
foreach ($fields[1] as $key => $value) {
if(isset($reportData[$value])){
$arrInHtml[] = "{{".$value."}}";
$valsForHtml[] = $reportData[$value];
}
}
$result = str_replace($arrInHtml,$valsForHtml,$html_form);
/*Eval start*/
preg_match_all('/{{=([A-Za-z0-9+\-\/{}* ]+?)=}}/', $result, $evals);
$arrInHtml = array();
$valsForHtml = array();
foreach ($evals[1] as $key => $value) {
$eval = "00";
$arrInHtml[] = "{{=".$value."=}}";
eval("\$eval= ".$value.";");
$valsForHtml[] = $eval;
}
$reportHTML = str_replace($arrInHtml,$valsForHtml,$result);
return $reportHTML;
}
$str = "invoice = {{invoice_no}}
customer = {{customer}}
item = {{item}}";
$data = ["invoice_no"=>"111","customer"=>"Niklesh Raut","item"=>"iphone"] ;
$newStr = putValuesInHTML($str,$data);
echo $newStr;
?>
Live demo
Input :
invoice = {{invoice_no}}
customer = {{customer}}
item = {{item}}
Output for $data = ["invoice_no"=>"111","customer"=>"Niklesh Raut","item"=>"iphone"] :
invoice = 111
customer = Niklesh Raut
item = iphone

PHP: Sorting MySQL result to multi-dimensional array

Now I'm tryin' to sort MySQL result to multi-dimensional array by type line in SQL
so, that's my code:
function getTableValues($table_name)
{
// $link = connect_db();
$front_end_query = "SELECT * FROM `".$table_name."` WHERE `type` = 'front_end'";
$front_end_query_result = mysql_query($front_end_query);
$cur_row = 0;
/*while ($line = mysql_fetch_assoc($queryresult))
{
$values = $line;
$cur_row++;
}*/
$front_end = mysql_fetch_assoc($front_end_query_result);
$i=0;
while ($line = mysql_fetch_assoc($front_end_query_result)){
#if ($line['type'] === 'front_end'){
# $line[$line['type']][$line['name']] = $line['value'];
# $line[$line['type']][$line['name']]['desc'] = $line['description'];
# $line[$line['type']][$line['name']]['visible_name'] = $line['visible_name'];
# $line[$line['type']][$line['name']]['write_roles'] = $line['write_roles'];
# $line[$line['type']][$line['name']]['read_roles'] = $line['read_roles'];
#}
$values['front_end'][$line['name']] = $line;
$i++;
}
return $values;
}
And my MySQL table:
id type write_roles read_roles name value description visible_name
1 front_end 0 any title sometitle exampletitle Title
2 front_end 0 any description somedesc example Description
And that's what I want to get:
$config[(someType)][(SomeName)] = (value of line)
$config[(someType)][(SomeName)][(SomeOption)] = (value of option)
E.g.: $config['front_end']['title']['description'] that returns exampletitle
How I can do that?
UPD0: so I tried to echo my array with foreach, and it's returned just one row from my DB.
What I doing wrong?
$values = array(); //base array
while ($line = mysql_fetch_assoc($front_end_query_result)){ //fetch the rows
//in the base array create a new array under 'name'
$values[$line['name']] = array();
//for each item in the result set, add it to the new array
foreach ($line as $key => $value) {
$values[$line['name']][$key] = $value;
}
}

PHP - Array inside the loop returns empty

I am trying to add data to 2 different MySql tables through a CSV upload. I have been able to retrieve the information and upload part of the information on one table, but I am having issues sending data to the second table. I have come up with the following code:
$i = 0;
//Loop through the csv file
do {
if ($data[0]) {
//Store request information
//Info for Request Table
$requester_email = $data[0];
$requester_name = $data[1];
$client_name = $data[2];
$client_country = $data[3];
$opportunity_number = $data[4];
$machine_quantity = $data[5];
$severity = $data[6];
//Store machine values
//Info for Serial Numbers Table
$serialType = array();
$serialModel = array();
$serialType[$i] = $data[7];
$serialModel[$i] = $data[8];
}
$i++;
} while ($data = fgetcsv($handle,1000,",","'"));
I am having an issue with the array. I have only been able to store the serialType and serialModel from the last line in the csv file. For example, if the csv file has 3 lines of data:
(
[0] => Empty
[1] => Empty
[2] => Last Value ok
)
How come I am unable to store the other two values?
Just move
$serialType = array();
$serialModel = array();
before do in your script. While it is still inside the do loop it is just a initialize variable in do - while scope each iteration and clean it up.
$i = 0;
$serialType = array();
$serialModel = array();
while ($data = fgetcsv($handle,1000,",","'")) {
...
$serialType[$i] = $data[7];
$serialModel[$i] = $data[8];
$i++;
};

php for each in while loop

I am trying to get specific data from a while loop and loop it x number of times.
I'm selecting this data:
$r=mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0 FROM advertisements WHERE token = '".$_GET['token']."'");
while ($adData = mysql_fetch_array($r, MYSQL_NUM))
{
$data = $adData;
$ac0 = $data['ac0'];
$ac1 = $data['ac0'];
print $ac0;
print $ac1;
}
This doesn't work. Nothing gets printed out.
What I want to do is to get ac6 to ac0 value for that specific advertisement (where token).
How can I do that?
Change your numeric fetch to an associative one, then add a foreach loop to process the result.
$r = mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0
FROM advertisements WHERE token = '" . $_GET['token'] . "'");
while ($adData = mysql_fetch_assoc($r))
{
foreach ($adData as $key => $value)
{
$nubmer = (int)substr($key, 2);
print $value; // or whatever you actually want to do
}
}
Also I hope you're validating $_GET['token'] against possible mischief in your code.
You can create an arrays to add the values from the result query
1st is to create an array:
$advert_AC0 = array();
$advert_AC1 = array();
$advert_AC2 = array();
$advert_AC3 = array();
$advert_AC4 = array();
$advert_AC5 = array();
$advert_AC6 = array();
Now, to add content to array
$r = mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0
FROM advertisements WHERE token = '" . $_GET['token'] . "'");
if(mysql_num_rows($r)){ //check 1st if there is num of rows from the result
while ($adData = mysql_fetch_assoc($r))
{
array_push($advert_AC0, $dData['ac0']);
array_push($advert_AC1, $dData['ac1']);
array_push($advert_AC2, $dData['ac2']);
array_push($advert_AC3, $dData['ac3']);
array_push($advert_AC4, $dData['ac4']);
array_push($advert_AC5, $dData['ac5']);
array_push($advert_AC6, $dData['ac6']);
}
}else{
echo "NO RESULT.";
}
to call for the array values, 1 by 1
$count_array = count($advert_AC0);
$i = $count_array;
while(1 <= $i){
echo "AC0: $advert_AC0[$i]<br>";
echo "AC1: $advert_AC1[$i]<br>";
echo "AC2: $advert_AC2[$i]<br>";
echo "AC3: $advert_AC3[$i]<br>";
echo "AC4: $advert_AC4[$i]<br>";
echo "AC5: $advert_AC5[$i]<br>";
echo "AC6: $advert_AC6[$i]<br>";
$i++;
}
I don't know if my answer solved your question, please comment if not.

Generate a comma separated list from Session Array

I have a session array [cart] of which contains user id numbers. I am trying to generate a list of email addresses from the contact table WHERE the contact id numbers in the session = the contact_id in the database.
Here is my code.
// Find cart members from the session array
foreach ($_SESSION['cart'] as $key=>$val) {
$contactid = $val;
// Query the database for cart members
$cartresult = mysql_query("SELECT contact.email FROM contact WHERE contact.contact_id = '$contactid'");
$emailresult = mysql_query($emailquery) or DIE (mysql_error());
while ($r = mysql_fetch_array($emailresult)) {
$emailAry[] = $r['email'];
}
}
// Create comma separated list from email array
if (count($emailAry)) {
$list = implode(", ", $emailAry);
$list = str_replace(" ,", "", $list);
Apparently there is no value for $emailAry because the if statement is being neglected.
Any idea why this would be?
$emailquery from my perspective is undefined.
$emailAry = array();
// Find cart members from the session array
foreach ($_SESSION['cart'] as $key=>$val) {
$cartresult = mysql_query("SELECT email FROM contact WHERE contact_id = '$val'");
while ($r = mysql_fetch_array($cartresult)) {
$emailAry[] = $r['email'];
}
}
// Create comma separated list from email array
if (count($emailAry)) {
$list = implode(",", $emailAry);
// no need to replace ', ' with '', implode will do all the job creating a CSV :)
//$list = str_replace(" ,", "", $list);
}
Declare the $emailAry array in the outer scope, so you can access it from the code out of the while and foreach, like his:
$emailAry = array();
foreach ($_SESSION['cart'] as $key=>$val) {
...
...
Use this it's easy and fast
$to = '';
foreach ($result->result() as $row){
$to .= $row->id.',';
}
$to = rtrim($to,',');
Change it according to yours.

Categories