PHP Last in array to CSV - php

I have been trying to get this code to work for ages now and have looked at other questions but it is not working for me. Any guidance is greatly appreciated.
In context, there is a sql query to bring back all of the results for today's entries. These are converted to a CSV file every day. To import into the software then the end of each row must return "" and a carriage return except the last row which should not add a carriage return.
The code is below:
$xo1 = "\"\"";
$xo2 = "\r\n";
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
if(++$i === $columns_total){
$xo1 = "";
$xo2 = "";}
}
$output .= $xo1;
$output .= $xo2;
}

I guess rtrim() should do the job, if I got the question right.
while ( $row = mysql_fetch_array( $sql ) ) {
foreach( $row as $column ) {
$output .= sprintf( '"%s",""' . "\r\n" , $column );
}
}
rtrim( $output, '""' . "\r\n" );

You can also use the index of the loop for this problem. When index is above zero apply the $xo1 and $xo2. For example:
for ($i = 0; $i < $columns_total; $i++) {
if ( $i > 0 ) {
$output .= $xo1 . $xo2;
}
// now apply other workings
$output .='"'.$row["$i"].'",';
}

Related

php code update split and count not working

I made some code updates from 5.6 to 7.4.11 and this section of code stopped working, Its not tossing an error so im a little unclear where I went wrong.
Original code
<?
$mapdesc = get_post_meta( $post->ID, 'the_mapdesc');
if (count($maxmapdesclength) > 0 )
{
if (strlen($mapdesc[0]) > $maxmapdesclength) $mapdesc[0] = substr($mapdesc[0], 0, $maxmapdesclength-3) . '...';
$arrmapdesc = split("\n", $mapdesc[0]);
$mymapdesc = "";
for ($i=0; $i<count($arrmapdesc) && $i<3; $i++)
$mymapdesc .= $arrmapdesc[$i] . '<br />';
print $mymapdesc;
}
Updated code
<?
$mapdesc = get_post_meta( $post->ID, 'the_mapdesc');
// if (count($maxmapdesclength) > 0 )
if (is_countable($maxmapdesclength) && count($maxmapdesclength) > 0 )
{
if (strlen($mapdesc[0]) > $maxmapdesclength) $mapdesc[0] = substr($mapdesc[0], 0, $maxmapdesclength-3) . '...';
$arrmapdesc = explode("\n", $mapdesc[0]);
$mymapdesc = "";
for ($i=0; $i<count($arrmapdesc) && $i<3; $i++)
$mymapdesc .= $arrmapdesc[$i] . '<br />';
print $mymapdesc;
}
I suspect there's something wrong with your usage of $maxmapdesclength.
In the if statement, you are treating it as a Countable|array, and within the substr function you are then expecting it to act like a number.

Getting Notice: Undefined offset: 0

I am getting this error in 3 spots in the function that I pasted below. There is more to this code, but I didn't think it was needed to get this thing figured out.
$count = count($collection);
$i = 1 ;
foreach ($collection as $product)
{
$j = 1 ;
$productId = $product->getDiamondsearchId();
$attributValueOptions = "[" ;
$attributValueOptions .= "'".$productId."', ";
foreach($filterAttributeIds as $filterAttributeId){
$attributValueCollection = Mage::getModel('diamondsearch/diamondsearchattributvalue')->getCollection()->addFieldToFilter('attribut_id',$filterAttributeId)->addFieldToFilter('diamondsearch_id',$productId)->getData();
$attrbutValueId = $attributValueCollection[0]['attrbut_value_id'];
//echo $attrbutValueId."<br>";
$attributValueOptionCollection = Mage::getModel('diamondsearch/diamondsearchattributoptionvalue')->getCollection()->addFieldToFilter('id',$attrbutValueId)->getData();
if($j == 1 && $attributValueOptionCollection[0]['attribut_value'] == ""){
break ;
}
if($j == 15){
$attributValueOptions .= "'".$attributValueOptionCollection[0]['attribut_value']."'";
}else{
$attributValueOptions .= "'".$attributValueOptionCollection[0]['attribut_value']."', ";
}
$j++;
}
if($count == $i ){
$attributValueOptions .= "]";
}else{
$attributValueOptions .= "], ";
}
$i++;
echo $attributValueOptions ;
}
The problem is with this line:
$attributValueCollection = Mage::getModel('diamondsearch/diamondsearchattributvalue')->getCollection()->addFieldToFilter('attribut_id',$filterAttributeId)->addFieldToFilter('diamondsearch_id',$productId)->getData();
$attrbutValueId = $attributValueCollection[0]['attrbut_value_id'];
You're trying to get the first item of array, but this variable is empty. You should verify and then do the stuff you want, like this:
if(!empty(attributValueCollection)){
$attrbutValueId = $attributValueCollection[0]['attrbut_value_id'];
Here's the complete gist:
https://gist.github.com/muriloazevedo/8dc5b11b17d1c4a3a518
But also is important to remember, if you trying to generate a json result, is better to use json_encode for that:
http://php.net/manual/pt_BR/function.json-encode.php

PHP SQL - Order By Date failing due to ","

I have a very strange issue. I am querying data and formatting it into a json. The format works great, but when i try to add a case that prevents a , from appearing in the last item of the json, the "Order By Date" of my SQL statement doesn't work, i just orders it by ID. Any thoughts why?
$sql = "SELECT * FROM events ORDER BY date";
$res = mysql_query($sql,$con);
$number = mysql_num_rows($res);
$json = 'var event_data={';
$i = 1;
while ($row = mysql_fetch_assoc($res))
{
$json .= '"'.$row['id'].'": {';
$json .= '"loc_id":"'.$row['loc_id'].'"';
$json .= ', "type":"'.$row['type'].'"';
$json .= ', "time":"'.$row['time'].'"';
$json .= ', "date":"'.$row['date'].'"}';
if ($i < $number)
{
$json .= ','; //<----- this is the problem child
}else{
$json .= '';
}
$i ++;
}
$json .= '};';
echo $json;
Please stop what you're doing now and check out: http://php.net/manual/en/function.json-encode.php
Building your own json encoder is going to be difficult to do correctly and will take quite take quite a bit of processing if you're doing it from PHP. Build up your data structure using PHP then encode the entire thing in one pass:
$o = array();
while ( $row = mysql_fetch_assoc($res) ) {
$n = array();
$n['loc_id'] = $row['loc_id'];
$n['type'] = $row['type'];
# ...
$o[ $row['id'] ] = $n;
}
echo json_encode($o);

PHP Foreach Loop and DOMNodeList

I am trying to determine the end of a foreach loop that is seeded with a collection of DOMNodeList. Currently, I am using a for loop would like to avoid having a 'magic' number there. I do know there are only going to be 8 columns, but I would like the code me generic for other applications.
Is it possible to convert this to a Foreach loop? I have tried the end() and next() functions, but they are not returning any data and I suspect that they only work on arrays and not this DOMNodeList collection.
The code is building a CSV file without the trailing ','
Current output is:
"Value 1","Value 2","Value 3","Value 4","Value 5","Value 6","Value 7","Value 8"
Here is an example of code:
$cols = $row->getElementsByTagName("td");
$printData = true;
// Throw away the header row
if ($isFirst && $printData) {
$isFirst = false;
continue;
}
for ($i = 0; $i <= 8; $i++) {
$output = iconv("UTF-8", "ASCII//IGNORE", $cols->item($i)->nodeValue);
$output2 = trim($output);
if ($i == 8) {
// Last Column
echo "\"" . $output2 . "\"" . "\n";
} else {
echo "\"" . $output2 . "\"" . ",";
}
}
You can use:
$cols->length
To retrieve the number of items in a DOMNodeList.
See http://php.net/manual/en/class.domnodelist.php
Edit:
If you change you're code to this, you don't have to worry about the trailing comma, or the length:
$output = array();
foreach ($cols as $item) {
$output = iconv("UTF-8", "ASCII//IGNORE", $item->nodeValue);
$output2 = trim($output);
$output[] = '"' . $output2 . '"';
}
$outputstring = implode(',', $output);
$cols->length
Should give you the number of items in the list
for ($i = 0; $i < $cols->length; $i++) {
// ...
if ($i == $cols->length - 1) {
// last column

Condition where the result is empty in PHP

$output = "<loginsuccess>";
for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
}
$output .= "</loginsuccess>";
I need now a simple condition where if the result is empty then i need to return no inside the xml [ login success ].
Is this a correct way....
if($row = mysql_fetch_array($result)) {
for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
} } else {
$output.="no";
}
if (mysql_num_rows($result) == 0) {
$output .= '<loginsuccess>no</loginsuccess>';
} else {
// your code
}
Try this instead:
$i = 1;
while($row = mysql_fetch_array($result))
{
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
$i++;
}
if ($i == 1)
$output .= "no";
Just a quick note, I would do what Schnalle does, but in your code I would change the for loop to a while loop as you are not doing anything with the $i
while($row = mysql_fetch_row($result)){
In total I would write you code like this:
$output = '<loginsucces>';
if(mysql_num_rows($result)){
while($row = mysql_fetch_row($result)){
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
}
} else {
$output .= 'no';
}
$output .= '</loginsucces>';
Also It owuld be even better not to mix logic and output, but that would be overkill in this situation.
Wont the for-loop simply be skipped when there are no rows? Otherwise you might want to use mysql_num_rows to count the number of rows in your result set.

Categories