Build grid rows based on columns widths array PHP - php

I have an array of column widths + content that I need to process and build row based on them.
$content = array(
'100',
'80',
'25',
'25',
'25',
'25',
'50',
'50',
'-1',
'33.333333333333',
'33.333333333333',
'33.333333333333',
'50',
'50',
'100',
'16.666666666667',
'-1'
);
-1 means that this is not a column , but a text or shortcode and it should not be wrapped in to row.
from the above array desired processed array should be
$content = array(
'[row]100[/row]',
'[row]80[/row]',
'[row]25',
'25',
'25',
'25[/row]',
'[row]50',
'50[/row]',
'-1',
'[row]33.333333333333',
'33.333333333333',
'33.333333333333[/row]',
'[row]50',
'50[/row]',
'[row]100[/row]',
'[row]16.666666666667[/row]',
'-1'
);
I have tried a loop with a starting accumulator 0 that I was adding width from loop but is simply buggy.
Any help is appreciated.

Map your array.
$start = [
'100',
'80',
'25',
// ...removed for brevity
];
function process(array $data) {
$output = array_map(function ($row, $index) use ($data) {
if ($row == '-1') {
return '-1';
}
$value = $row;
$previousIndex = $index - 1;
$nextIndex = $index + 1;
// Check previous row
if (
// There's a row and it's different
(isset($data[$previousIndex]) && $data[$previousIndex] != $row)
||
// There's no row, we're on the beggining of the list
!isset($data[$previousIndex])
) {
$value = '[row]' . $value;
}
// Check next row
if (
// There is a next row and it's different
(isset($data[$nextIndex]) && $data[$nextIndex] != $row)
||
// There's no next row, we're on the end of the list
!isset($data[$nextIndex])
) {
$value = $value . '[/row]';
}
return $value;
}, $data, array_keys($data));
return $output;
}

$sum = 100;
$new_content = array();
$prev = false;
for($i=0;$i<count($content);$i++){
$num = $content[$i];
$diff = $sum-$num;
echo $num.'=>'.$diff.',';
if(!$prev && $diff==0){
$new_content[] = "[row]".$content[$i]."[/row]";
}
if($diff==0 && $prev){
$new_content[] = $content[$i]."[/row]";
$sum=100;
$prev = false;
}
if($diff>0 && $diff<100 && $prev && $content[$i]!=-1){
$new_content[] = $content[$i];
$sum = $diff;
$prev = true;
}
if($diff>0 && $diff<100 && !$prev){
$new_content[] = "[row]".$content[$i];
$sum = $diff;
$prev = true;
}
if($diff<0){
$new_content[] = "[/row][row]".$content[$i];
$sum = 100-$content[$i];
$prev = true;
}
if($content[$i]==-1 && $prev){
$new_content[] = "[/row]".$content[$i];
}else if($content[$i]==-1){
$new_content[] = $content[$i];
}
}
print_r($new_content);

Related

How to loop through a foreach until X is found, if not found, look for Y

Sorry if this is a duplicate, I can't figure out what to search for to find the answer.
I have a foreach loop, and in that loop, I'm attempting to test if (A == B). Then once found I break the loop. If (A != B) in an iteration, I test if (X == Y).
My problem is that if (X == Y) is found to be true first, the loop breaks before if (A == B) can be tested.
Is there a better way to accomplish this task?
$variable[1] = ['A' => 'n', 'X' => 'n'];
$variable[2] = ['A' => 'n', 'X' => 'Y'];
$variable[3] = ['A' => 'B', 'X' => 'n'];
$test = 'B';
foreach ($variable as $value) {
if($value['A'] == $test || $value['X'] == "Y") {
echo 'The results: ' . $value['A'];
break;
}
}
// The results for $variable[2] are returned. I need the results for $variable[3] to be returned.
I did have an else statement which worked fine, but I was having to duplicate the output.
Thanks in advance!
The code above is a simplified version of what I'm working on. Here's the code I'm working actually working on.
foreach ($product_xml->products->product_styles as $style => $attribute) {
if(isset($_GET['color']) && $attribute['color'] == $color_selected || $attribute['is_default'] == "1") {
foreach ($attribute as $value){
$imgURL = (string)$value['imgurl'];
$thumburl = (string)$value['thumburl'];
$thumburl_array[(string)$value['side']] = (string)$value['thumburl'];
if (in_array($imgURL, $values)){continue;}
else{
array_push($values, $imgURL);
$imgURL = str_replace("REPLACE_DOMAIN_WITH",IDEQ_INKSOFTAPI_URL_SECURE,$imgURL );
$thumburl = str_replace("REPLACE_DOMAIN_WITH",IDEQ_INKSOFTAPI_URL_SECURE,$thumburl );
$thumburl = str_replace("150.png","500.png",$thumburl );
echo '<img src="'.$imgURL.'" class="pic'.$counter.'" title="'.$value['name'].'">';
$counter++;
}
}
break;
}
}
Use a temporary variable and move the echo to after the foreach.
$variable[1] = ['A' => 'n', 'X' => 'n'];
$variable[2] = ['A' => 'n', 'X' => 'Y'];
$variable[3] = ['A' => 'B', 'X' => 'n'];
$test = 'B';
$output = null;
foreach ($variable as $value) {
if($value['A'] == $test) {
$output = $value['A'];
break;
} else if ($output == null && $value['X'] == "Y") {
$output = $value['X'];
}
}
echo 'The results: ' . $output;
Here is my approximation with a function:
function search($variable, $test){
$alternative = null;
foreach($variable as $value){
if($value['A'] == $test){
return $value['A'];
}
if($value['X'] == 'Y' && $alternative === null){
$alternative = $value['A'];
}
}
return $alternative;
}
It will return first coincidence on A and if not found, first coincidence on X.
This way you only loop through foreach once.
Instead of looping you can use array_column to isolate one column of the array A or X.
Then use in_array to see if you find the $test in the array.
$test = 'B';
$test2 = 'Y';
If(in_array($test, array_column($variable, "A"))){
Echo $test . " Found in A";
}Else if(in_array($test2, array_column($variable, "X"))){
Echo $test2 . " Found in B";
}else{
Echo "none found";
}
https://3v4l.org/dv7Yp
Based off of the response from James Lalor I've come to this solution. If anyone sees a better/more optimal way of handling this, I'd love to hear!
$counter = 1;
$values = array();
$thumburl_array = array();
$found = false;
$find_default = false;
$style_count = count($product_xml->products->product_styles);
for ($i=0; $i < $style_count; $i++) {
if (isset($_GET['color']) && $product_xml->products->product_styles[$i]['color'] == $color_selected) {
$found = true;
} elseif (!$found && !$find_default && $i == $style_count - 1) {
$find_default = true;
$i = 0;
}
if ($find_default && $product_xml->products->product_styles[$i]['is_default'] == '1') {
$found = true;
}
if ($found) {
foreach ($product_xml->products->product_styles[$i] as $value){
$imgURL = (string)$value['imgurl'];
$thumburl = (string)$value['thumburl'];
$thumburl_array[(string)$value['side']] = (string)$value['thumburl'];
if (in_array($imgURL, $values)){continue;}
else{
array_push($values, $imgURL);
$imgURL = str_replace("REPLACE_DOMAIN_WITH",IDEQ_INKSOFTAPI_URL_SECURE,$imgURL );
$thumburl = str_replace("REPLACE_DOMAIN_WITH",IDEQ_INKSOFTAPI_URL_SECURE,$thumburl );
$thumburl = str_replace("150.png","500.png",$thumburl );
echo '<img src="'.$imgURL.'" class="pic'.$counter.'" title="'.$value['name'].'">';
$counter++;
}
}
break;
}
}
Simplified version
$variable[] = ['A' => 'n', 'X' => 'n', 'result' => 'do'];
$variable[] = ['A' => 'n', 'X' => 'Y', 'result' => 're'];
$variable[] = ['A' => 'B', 'X' => 'n', 'result' => 'mi'];
$found = false;
$find_default = false;
$count = count($variable);
$test = 'B';
for ($i=0; $i < $count; $i++) {
if ($variable[$i]['A'] == $test) {
$found = true;
} elseif (!$found && !$find_default && $i == $count - 1) {
$find_default = true;
$i = 0;
continue;
}
if ($find_default && $variable[$i]['X'] == 'Y') {
$found = true;
}
if ($found) {
echo "Resulsts: " . $variable[$i]['result'];
break;
}
}
Thank you all for your feedback, much appreciated. Cheers.

I want to find my value in an array using just 1 foreach

I have an array lets suppose
$myarr = array(
'1',
'2',
'3',
'4-7',
'9',
'10',
)
$search2 = '2';
$search5 = '5';
I want to check both these 2 variables inside my $myarr. The first one can be easily found by using in_array but the $search5 is there inside '4-7' but what will I do to find the value? I don't want 2 foreach because i know I can use explode and then compare the start and end value. Is there a single or double line function that could help me achieve what I need? Thanks
PHP code demo
<?php
ini_set("display_errors", 1);
$search=2;
$result=null;
$myarr = array(
'1',
'2',
'3',
'4-7',
'9',
'10',
);
echo search_in_array($myarr,$search);
function search_in_array($myarr,$search)
{
$result=false;
array_map(function($number) use ($myarr,$search, &$result){
if(preg_match("/^(\d+)\-(\d+)$/", $number,$matches))
{
if(in_array($search,range($matches[1],$matches[2])))
{
$result= true;
}
}
elseif(preg_match("/^(\d+)$/", $number,$matches))
{
if(in_array($search,$myarr))
{
$result= true;
}
}
}, $myarr);
return $result;
}
Just as another answer:
$myarr = [
'1',
'2',
'3',
'4-7',
'9',
'10',
];
$search2 = '2';
$search5 = '5';
$search12 = '12';
function myInArray($needle, $haystack) {
return in_array(
$needle,
array_reduce(
$haystack,
function($incrementor, $value) {
return array_merge($incrementor, (strpos($value, '-') !== false) ? range(...explode('-', $value)) : [(int)$value]);
},
[]
)
);
}
foreach([$search2, $search5, $search12] as $searchValue) {
echo $searchValue, " is ",(myInArray($searchValue, $myarr) ? '' : 'NOT '), "in the array", PHP_EOL;
}
Probably not as efficient, especially when working with larger ranges of values in $myarr, but a slightly different approach
Demo
Here is almost one-liner,
$search = '5';
$matches = explode('-',array_values(preg_grep('/[-]/', $myarr))[0]);
if(in_array($search, $myarr)|| in_array($search,range($matches[0],$matches[1]))){
echo "found";
}else{
echo "not found";
}
I am exploding by - and then creating range with that and checking that with in_array.
Here is working DEMO
<?php
$myarr = ['1', '2', '3', '4-7', '9', '10'];
$search_array = [2, 5];
$search_results = [];
for ($i = 0; $i < count($search_array); $i++) {
$search_results[$search_array[$i]] = array_search($search_array[$i], $myarr);
if (!$search_results[$search_array[$i]]) {
foreach ($myarr as $value) {
if (strpos($value, "-") !== false) {
$data = explode("-", $value);
if ($search_array[$i] >= $data[0] && $search_array[$i] <= $data[1]) {
$search_results[$search_array[$i]] = array_search($value, $myarr);
}
}
}
}
if (!$search_results[$search_array[$i]]) {
unset($search_results[$search_array[$i]]);
}
}
var_dump($search_results);
Obviously using single foreach i cam up with this code to find ... set of data another is for loop not foreach.
#Ali Zia you can also try this logic like below:
<?php
$myarr = array(
'1',
'2',
'3',
'4-7',
'9',
'10',
);
$flag = 0;
$search = '5';
foreach($myarr as $value){
if($value == $search){
$flag = 1;
break;
}
else if(strpos($value, "-")){
$numberRange = explode("-", $value);
if($numberRange[0] <= $search && $numberRange[1] >= $search){
$flag = 1;
break;
}
}
}
if($flag == 1){
echo "yes number found in the array";
}
else{
echo "sorry not found";
}
Just for the sake of using range() and argument unpacking, because none of the other answers do:
function in_array_range($needle, array $haystack) {
if (in_array((int) $needle, $haystack, true)) {
return true;
}
$haystack = array_map(
function($element) {
return strpos($element, '-')
? range(... explode('-', $element, 2))
: (int) $element;
},
$haystack
);
foreach ($haystack as $element) {
if (is_array($element) && in_array((int) $needle, $element, true)) {
return true;
}
}
return false;
}
The function below returns the index of $needle in $haystack or -1 if no such element has been found.
function find(array $haystack, $needle) {
for ($i = 0; $i < count($haystack); $i++) {
$parts = explode("-", $haystack[$i]);
if (count($parts) == 2) {
if ($needle >= $parts[0] && $needle <= $parts[1]) {
return $i;
}
}
else if ($needle == $parts[0]) {
return $i;
}
}
return -1;
}
The function assumes that $array only contains a single non-negative integer or two non-negative integers separated by a dash.
You can now collect the indices like this:
$indices = array();
foreach ($searchValues as $searchValue) {
$indices[] = find($myarr, $searchValue);
}
Try with following code :
$myarr = array('1','2','3','4-7','9','10');
$search = 1; // Try with 5
$flag1 = false;
foreach($myarr as $number){
if(!is_numeric($number)){
list($start,$end) = explode("-",$number);
if($search >=$start && $search <=$end ){
echo $search .' Found';
}
}else if($flag1 == false){
if(in_array($search,$myarr)){
echo $search .' Found';
$flag1 = true;
}
}
}
Working Demo
I know the answer has already been accepted but here is my approach w/ and w/o using foreach.
(See demo).
With foreach :
<?php
$value = 3;
foreach($myarr as $myval){
list($start, $end) = strpos($myval, '-') ? explode('-', $myval) : [$myval, $myval];
if($value >= $start && $value <= $end){
echo $value . ' found between "' . $start . '" & "' . $end . '" !' . "\n";
}
}
Without foreach, "one line" code :
<?php
$value = 5;
$trueValues = [1,5];
$falseValues = [5, 7, 8];
var_dump(!count(array_diff($trueValues,array_reduce($myarr,function($arr, $item){return $arr + (strpos($item, '-') ? range(...explode('-', $item)) : [$item]);},[]))));
var_dump(!count(array_diff($falseValues,array_reduce($myarr,function($arr, $item){return $arr + (strpos($item, '-') ? range(...explode('-', $item)) : [$item]);},[]))));
var_dump(in_array($value, array_reduce($myarr, function($arr, $item){return $arr + (strpos($item, '-') ? range(...explode('-', $item)) : [$item]);}, array())));
Unfolded :
<?php
var_dump(
!count(
array_diff(
$trueValues,
array_reduce(
$myarr,
function($arr, $item){
return $arr + (strpos($item, '-') ? range(...explode('-', $item)) : [$item]);
},
[]
)
)
)
);
EDIT : Didn't know the ellipsis operator, thank you #Mark Baker

Saving reservations using available 2 halls

Below is the function for saving some reservation details to the database. get_hall() query returns 2 halls(haal1 and hall2). bus when going to the database only hall1 is inserting. I want to insert hall1 next reservation hall2. How to improve below code.
function save_reserve_detail($date,$time,$flag){
$halls = $this->halls_model->get_hall();
foreach ($halls AS $each) {
$hall = $each['hall_id'];
break;
}
$reference_no = date("YmdHis");
if ($flag == 1) {
$hall_id = $hall;
$type = 1;
$date = $date;
} else if ($flag == 2) {
$hall_id = $hall;
$type = 0;
$date = $date;
}
$data = array(
'reference_no' => $reference_no,
'date' => $date,
'type' => $type,
'hall' => $hall
);
$result = $this->db->insert('reserving_details', $data);
if ($result) {
return $reference_no;
} else {
return 0;
}
}
Remove the break from foreach . now the $hall contains an array of 2 values. now use a for loop to insert the value into the table.
<?php
function save_reserve_detail($date,$time,$flag){
$halls = $this->halls_model->get_hall();
foreach ($halls AS $each) {
$hall = $each['hall_id'];
// break;
}
$reference_no = date("YmdHis");
if ($flag == 1) {
$hall_id = $hall;
$type = 1;
$date = $date;
} else if ($flag == 2) {
$hall_id = $hall;
$type = 0;
$date = $date;
}
for($i=0;$i<sizeof($hall);$i++){
$data = array(
'reference_no' => $reference_no,
'date' => $date,
'type' => $type,
'hall' => $hall[$i]
);
$result = $this->db->insert('reserving_details', $data);
if ($result) {
return $reference_no;
} else {
return 0;
}
}
}
?>
Even you can alter your insert('reserving_details', $data); code which can handle array insertion.

Holding Array of Values with Codeigniter ruri_to_assoc()

I'm constructing a gallery which will use the URI to define a set of filter settings. CodeIgniter's ruri_to_assoc() works brilliantly for the majority of my settings as they are as simple as key=>value. However, one value (tags) can contain a number of values that I wish to match against.
As ruri_to_assoc() works off a key/val pairing, how would I set an array to a key in the url? Example:
/days/365/order/oldest/tag/car/tag/red/tag/mustang
At the moment, it looks like I'm going to have to explode the uri_string() and cycle through it myself. Like so:
$test_fil = explode('/',$this->uri->uri_string());
unset($test_fil[0]);
$val = 'key';
foreach($test_fil as $fkey=>$fval){
if($fval=='tags'){
$val = 'tag';
$new_filter['tags'] = '';
}
else{
if($val == 'key'){
$new_filter[$fval] = '';
$val = 'val';
$current_key = $fval;
}
elseif($val == 'val'){
$new_filter[$current_key] = $fval;
$val = 'key';
}
else{
$new_filter['tags'][] = $fval;
}
}
}
Is there something in CI that can do this for me?
We just need to make sure that uri_to_assoc will not override already existing keys when building the array.
In application/core create MY_URI.php :
class MY_URI extends CI_URI
{
protected function _uri_to_assoc($n = 3, $default = array(), $which = 'segment')
{
if ( ! is_numeric($n))
{
return $default;
}
if (isset($this->keyval[$which], $this->keyval[$which][$n]))
{
return $this->keyval[$which][$n];
}
$total_segments = "total_{$which}s";
$segment_array = "{$which}_array";
if ($this->$total_segments() < $n)
{
return (count($default) === 0)
? array()
: array_fill_keys($default, NULL);
}
$segments = array_slice($this->$segment_array(), ($n - 1));
$i = 0;
$lastval = '';
$retval = array();
foreach ($segments as $seg)
{
/*HERE IS THE PART WE TRULY OVERRIDE*/
if ($i % 2)
{
if(is_array($retval[$lastval]))
$retval[$lastval][] = $seg;
else
$retval[$lastval] = $seg;
}
else
{
if(isset($retval[$seg]) && !is_array($retval[$seg]))
{
$tmp = $retval[$seg];
$retval[$seg] = array();
$retval[$seg][] = $tmp;
}
else if(!isset($retval[$seg]))
{
$retval[$seg] = NULL;
$lastval = $seg;
}
}
/*END OVERRIDE*/
$i++;
}
if (count($default) > 0)
{
foreach ($default as $val)
{
if ( ! array_key_exists($val, $retval))
{
$retval[$val] = NULL;
}
}
}
// Cache the array for reuse
isset($this->keyval[$which]) OR $this->keyval[$which] = array();
$this->keyval[$which][$n] = $retval;
return $retval;
}
}
And then in your controller, nothing change :
$myTags = $this->uri->uri_to_assoc();
Here is what I get after testing :
array (size=3)
'days' => string '365' (length=3)
'order' => string 'oldest' (length=6)
'tag' =>
array (size=3)
0 => string 'car' (length=3)
1 => string 'red' (length=3)
2 => string 'mustang' (length=7)

How To Delete The Top 100 Rows From a CSV File With PHP

I have a php script running on a regular basis that processes the top 100 rows of a CSV file. When it is done I want it to delete the processed rows from the CSV file.
I have tried the below code, but it does not delete anything. I am not sure the best way to state the condition in PHP and am not sure what to put for the $id. I set the number of rows at 5 for testing purposes. Likely have somy syntax wrong.
Any suggestions? Tips?
function delete_line($id)
{
if($id)
{
$file_handle = fopen("file.csv", "w+");
$myCsv = array();
while (!feof($file_handle) )
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($id != $line_of_text[0])
{
fputcsv($file_handle, $line_of_text);
}
}
fclose($file_handle);
}
}
$in = fopen( 'file.csv', 'r');
$out = fopen( 'file.csv', 'w');
// Check whether they opened
while( $row = fgetcsv( $in, $cnt)){
fputcsv( $out, $row);
}
fclose( $in); fclose( $out);
Whole script is here...
<?php
require_once('wp-config.php');
$siteurl = get_site_url();
//print_r($_FILES);
//if($_FILES['file']['tmp_name']) {
//$upload = ABSPATH . 'file.csv';
//move_uploaded_file($_FILES['file']['tmp_name'], $upload);
//}
function clearer($str) {
//$str = iconv("UTF-8", "UTF-8//IGNORE", $str);
$str = utf8_encode($str);
$str = str_replace("’", "'", $str);
$str = str_replace("–", "-", $str);
return htmlspecialchars($str);
}
//file read
if(file_exists("file.csv")) $csv_lines = file("file.csv");
if(is_array($csv_lines)) {
$cnt = 5;
for($i = 0; $i < $cnt; $i++) {
$line = $csv_lines[$i];
$line = trim($line);
$first_char = true;
$col_num = 0;
$length = strlen($line);
for($b = 0; $b < $length; $b++) {
if($skip_char != true) {
$process = true;
if($first_char == true) {
if($line[$b] == '"') {
$terminator = '",';
$process = false;
}else
$terminator = ',';
$first_char = false;
}
if($line[$b] == '"'){
$next_char = $line[$b + 1];
if($next_char == '"')
$skip_char = true;
elseif($next_char == ',') {
if($terminator == '",') {
$first_char = true;
$process = false;
$skip_char = true;
}
}
}
if($process == true){
if($line[$b] == ',') {
if($terminator == ',') {
$first_char = true;
$process = false;
}
}
}
if($process == true)
$column .= $line[$b];
if($b == ($length - 1)) {
$first_char = true;
}
if($first_char == true) {
$values[$i][$col_num] = $column;
$column = '';
$col_num++;
}
}
else
$skip_char = false;
}
}
$values = array_values($values);
//print_r($values);
/*************************************************/
if(is_array($values)) {
//file.csv read
for($i = 0; $i < count($values); $i++) {
unset($post);
//check duplicate
//$wpdb->show_errors();
$wpdb->query("SELECT `ID` FROM `" . $wpdb->prefix . "posts`
WHERE `post_title` = '".clearer($values[$i][0])."' AND `post_status` = 'publish'");
//echo $wpdb->num_rows;
if($values[$i][0] != "Name" && $values[$i][0] != "" && $wpdb->num_rows == 0) {
$post['name'] = clearer($values[$i][0]);
$post['Address'] = clearer($values[$i][1]);
$post['City'] = clearer($values[$i][2]);
$post['Categories'] = $values[$i][3];
$post['Tags'] = $values[$i][4];
$post['Top_image'] = $values[$i][5];
$post['Body_text'] = clearer($values[$i][6]);
//details
for($k = 7; $k <= 56; $k++) {
$values[$i][$k] != '' ? $post['details'] .= "<em>".clearer($values[$i][$k])."</em>\r\n" : '';
}
//cats
$categoryes = explode(";", $post['Categories']);
foreach($categoryes AS $category_name) {
$term = term_exists($category_name, 'category');
if (is_array($term)) {
//category exist
$cats[] = $term['term_id'];
}else{
//add category
wp_insert_term( $category_name, 'category' );
$term = term_exists($category_name, 'category');
$cats[] = $term['term_id'];
}
}
//top image
if($post['Top_image'] != "") {
$im_name = md5($post['Top_image']).'.jpg';
$im = #imagecreatefromjpeg($post['Top_image']);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['topimage'] = '<img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" />';
}
}
//bottom images
for($k = 57; $k <= 76; $k++) {
if($values[$i][$k] != '') {
$im_name = md5($values[$i][$k]).'.jpg';
$im = #imagecreatefromjpeg($values[$i][$k]);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['images'] .= '<img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" />';
}
}
}
$post = array_map( 'stripslashes_deep', $post );
//print_r($post);
//post created
$my_post = array (
'post_title' => $post['name'],
'post_content' => '
<em>Address: '.$post['Address'].'</em>
'.$post['topimage'].'
'.$post['Body_text'].'
<!--more-->
'.$post['details'].'
'.$post['images'].'
',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $cats
);
unset($cats);
//add post
//echo "ID:" .
$postid = wp_insert_post($my_post); //post ID
//tags
wp_set_post_tags( $postid, str_replace(';',',',$post['Tags']), true ); //tags
echo $post['name']. ' - added. ';
//google coords
$address = preg_replace("!\((.*?)\)!si", " ", $post['Address']).', '.$post['City'];
$json = json_decode(file_get_contents('http://hicon.by/temp/googlegeo.php?address='.urlencode($address)));
//print_r($json);
if($json->status == "OK") {
//нашло адрес
$google['status'] = $json->status;
$params = $json->results[0]->address_components;
if(is_array($params)) {
foreach($params AS $id => $p) {
if($p->types[0] == 'locality') $google['locality_name'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_2') $google['sub_admin_code'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_1') $google['admin_code'] = $p->short_name;
if($p->types[0] == 'country') $google['country_code'] = $p->short_name;
if($p->types[0] == 'postal_code') $google['postal_code'] = $p->short_name;
}
}
$google['address'] = $json->results[0]->formatted_address;
$google['location']['lat'] = $json->results[0]->geometry->location->lat;
$google['location']['lng'] = $json->results[0]->geometry->location->lng;
//print_r($params);
//print_r($google);
//insert into DB
$insert_code = $wpdb->insert( $wpdb->prefix . 'geo_mashup_locations',
array( 'lat' => $google['location']['lat'], 'lng' => $google['location']['lng'], 'address' => $google['address'],
'saved_name' => $post['name'], 'postal_code' => $google['postal_code'],
'country_code' => $google['country_code'], 'admin_code' => $google['admin_code'],
'sub_admin_code' => $google['sub_admin_code'], 'locality_name' => $google['locality_name'] ),
array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
);
if($insert_code) {
$google_code_id = $wpdb->insert_id;
$geo_date = date( 'Y-m-d H:i:s' );
$wpdb->insert(
$wpdb->prefix . 'geo_mashup_location_relationships',
array( 'object_name' => 'post', 'object_id' => $postid, 'location_id' => $google_code_id, 'geo_date' => $geo_date ),
array( '%s', '%s', '%s', '%s' )
);
}else{
//can't insert data
}
echo ' address added.<br />';
}else{
//echo $json->status;
}
}
} //$values end (for)
}
}else{
//not found file.csv
echo 'not found file.csv';
}
function delete_line($id)
{
if($id)
{
$file_handle = fopen("file.csv", "w+");
$myCsv = array();
while (!feof($file_handle) )
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($id != $line_of_text[0])
{
fputcsv($file_handle, $line_of_text);
}
}
fclose($file_handle);
}
}
$in = fopen( 'file.csv', 'r');
$out = fopen( 'file.csv', 'w');
// Check whether they opened
while( $row = fgetcsv( $in, $cnt)){
fputcsv( $out, $row);
}
fclose( $in); fclose( $out);
?>
Update
I tried one of the answer codes and got a server error. Code below, thoughts?
<?php
require_once('wp-config.php');
$siteurl = get_site_url();
//print_r($_FILES);
//if($_FILES['file']['tmp_name']) {
//$upload = ABSPATH . 'file.csv';
//move_uploaded_file($_FILES['file']['tmp_name'], $upload);
//}
function clearer($str) {
//$str = iconv("UTF-8", "UTF-8//IGNORE", $str);
$str = utf8_encode($str);
$str = str_replace("’", "'", $str);
$str = str_replace("–", "-", $str);
return htmlspecialchars($str);
}
//file read
if(file_exists("file.csv")) $csv_lines = file("file.csv");
if(is_array($csv_lines)) {
$cnt = 5;
for($i = 0; $i < $cnt; $i++) {
$line = $csv_lines[$i];
$line = trim($line);
$first_char = true;
$col_num = 0;
$length = strlen($line);
for($b = 0; $b < $length; $b++) {
if($skip_char != true) {
$process = true;
if($first_char == true) {
if($line[$b] == '"') {
$terminator = '",';
$process = false;
}else
$terminator = ',';
$first_char = false;
}
if($line[$b] == '"'){
$next_char = $line[$b + 1];
if($next_char == '"')
$skip_char = true;
elseif($next_char == ',') {
if($terminator == '",') {
$first_char = true;
$process = false;
$skip_char = true;
}
}
}
if($process == true){
if($line[$b] == ',') {
if($terminator == ',') {
$first_char = true;
$process = false;
}
}
}
if($process == true)
$column .= $line[$b];
if($b == ($length - 1)) {
$first_char = true;
}
if($first_char == true) {
$values[$i][$col_num] = $column;
$column = '';
$col_num++;
}
}
else
$skip_char = false;
}
}
$values = array_values($values);
//print_r($values);
/*************************************************/
if(is_array($values)) {
//file.csv read
for($i = 0; $i < count($values); $i++) {
unset($post);
//check duplicate
//$wpdb->show_errors();
$wpdb->query("SELECT `ID` FROM `" . $wpdb->prefix . "posts`
WHERE `post_title` = '".clearer($values[$i][0])."' AND `post_status` = 'publish'");
//echo $wpdb->num_rows;
if($values[$i][0] != "Name" && $values[$i][0] != "" && $wpdb->num_rows == 0) {
$post['name'] = clearer($values[$i][0]);
$post['Address'] = clearer($values[$i][1]);
$post['City'] = clearer($values[$i][2]);
$post['Categories'] = $values[$i][3];
$post['Tags'] = $values[$i][4];
$post['Top_image'] = $values[$i][5];
$post['Body_text'] = clearer($values[$i][6]);
//details
for($k = 7; $k <= 56; $k++) {
$values[$i][$k] != '' ? $post['details'] .= "<em>".clearer($values[$i][$k])."</em>\r\n" : '';
}
//cats
$categoryes = explode(";", $post['Categories']);
foreach($categoryes AS $category_name) {
$term = term_exists($category_name, 'category');
if (is_array($term)) {
//category exist
$cats[] = $term['term_id'];
}else{
//add category
wp_insert_term( $category_name, 'category' );
$term = term_exists($category_name, 'category');
$cats[] = $term['term_id'];
}
}
//top image
if($post['Top_image'] != "") {
$im_name = md5($post['Top_image']).'.jpg';
$im = #imagecreatefromjpeg($post['Top_image']);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['topimage'] = '<img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" />';
}
}
//bottom images
for($k = 57; $k <= 76; $k++) {
if($values[$i][$k] != '') {
$im_name = md5($values[$i][$k]).'.jpg';
$im = #imagecreatefromjpeg($values[$i][$k]);
if ($im) {
imagejpeg($im, ABSPATH.'images/'.$im_name);
$post['images'] .= '<img class="alignnone size-full" src="'.$siteurl.'/images/'.$im_name.'" alt="" />';
}
}
}
$post = array_map( 'stripslashes_deep', $post );
//print_r($post);
//post created
$my_post = array (
'post_title' => $post['name'],
'post_content' => '
<em>Address: '.$post['Address'].'</em>
'.$post['topimage'].'
'.$post['Body_text'].'
<!--more-->
'.$post['details'].'
'.$post['images'].'
',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $cats
);
unset($cats);
//add post
//echo "ID:" .
$postid = wp_insert_post($my_post); //post ID
//tags
wp_set_post_tags( $postid, str_replace(';',',',$post['Tags']), true ); //tags
echo $post['name']. ' - added. ';
//google coords
$address = preg_replace("!\((.*?)\)!si", " ", $post['Address']).', '.$post['City'];
$json = json_decode(file_get_contents('http://hicon.by/temp/googlegeo.php?address='.urlencode($address)));
//print_r($json);
if($json->status == "OK") {
//нашло адрес
$google['status'] = $json->status;
$params = $json->results[0]->address_components;
if(is_array($params)) {
foreach($params AS $id => $p) {
if($p->types[0] == 'locality') $google['locality_name'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_2') $google['sub_admin_code'] = $p->short_name;
if($p->types[0] == 'administrative_area_level_1') $google['admin_code'] = $p->short_name;
if($p->types[0] == 'country') $google['country_code'] = $p->short_name;
if($p->types[0] == 'postal_code') $google['postal_code'] = $p->short_name;
}
}
$google['address'] = $json->results[0]->formatted_address;
$google['location']['lat'] = $json->results[0]->geometry->location->lat;
$google['location']['lng'] = $json->results[0]->geometry->location->lng;
//print_r($params);
//print_r($google);
//insert into DB
$insert_code = $wpdb->insert( $wpdb->prefix . 'geo_mashup_locations',
array( 'lat' => $google['location']['lat'], 'lng' => $google['location']['lng'], 'address' => $google['address'],
'saved_name' => $post['name'], 'postal_code' => $google['postal_code'],
'country_code' => $google['country_code'], 'admin_code' => $google['admin_code'],
'sub_admin_code' => $google['sub_admin_code'], 'locality_name' => $google['locality_name'] ),
array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
);
if($insert_code) {
$google_code_id = $wpdb->insert_id;
$geo_date = date( 'Y-m-d H:i:s' );
$wpdb->insert(
$wpdb->prefix . 'geo_mashup_location_relationships',
array( 'object_name' => 'post', 'object_id' => $postid, 'location_id' => $google_code_id, 'geo_date' => $geo_date ),
array( '%s', '%s', '%s', '%s' )
);
}else{
//can't insert data
}
echo ' address added.<br />';
}else{
//echo $json->status;
}
}
} //$values end (for)
}
}else{
//not found file.csv
echo 'not found file.csv';
}
function csv_delete_rows($filename='file.csv', $startrow=1, $endrow=5, $inner=false) {
$status = 0;
//check if file exists
if (file_exists($filename)) {
//end execution for invalid startrow or endrow
if ($startrow < 0 || $endrow < 0 || $startrow > 0 && $endrow > 0 && $startrow > $endrow) {
die('Invalid startrow or endrow value');
}
$updatedcsv = array();
$count = 0;
//open file to read contents
$fp = fopen($filename, "r");
//loop to read through csv contents
while ($csvcontents = fgetcsv($fp)) {
$count++;
if ($startrow > 0 && $endrow > 0) {
//delete rows inside startrow and endrow
if ($inner) {
$status = 1;
if ($count >= $startrow && $count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
//delete rows outside startrow and endrow
else {
$status = 2;
if ($count < $startrow || $count > $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
}
else if ($startrow == 0 && $endrow > 0) {
$status = 3;
if ($count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($endrow == 0 && $startrow > 0) {
$status = 4;
if ($count >= $startrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($startrow == 0 && $endrow == 0) {
$status = 5;
} else {
$status = 6;
}
}//end while
if ($status < 5) {
$finalcsvfile = implode("\n", $updatedcsv);
fclose($fp);
$fp = fopen($filename, "w");
fwrite($fp, $finalcsvfile);
}
fclose($fp);
return $status;
} else {
die('File does not exist');
}
}
?>
<html>
<body>
<form enctype="multipart/form-data" method="post">
CSV: <input name="file" type="file" />
<input type="submit" value="Send File" />
</form>
</body>
</html>
Here is php code for that:
$input = explode("\n", file_get_contents("file.csv"));
foreach ($input as $line) {
// process all lines.
}
// This function removes first 100 elements.
// More info:
// http://php.net/manual/en/function.array-slice.php
$output = array_slice($input, 100);
file_put_contents("out.csv", implode("\n", $output));
Note, if csv file contains header you have to remove first element from array $input.
I used this script in the passed written by Joby Joseph:
function csv_delete_rows($filename=NULL, $startrow=0, $endrow=0, $inner=true) {
$status = 0;
//check if file exists
if (file_exists($filename)) {
//end execution for invalid startrow or endrow
if ($startrow < 0 || $endrow < 0 || $startrow > 0 && $endrow > 0 && $startrow > $endrow) {
die('Invalid startrow or endrow value');
}
$updatedcsv = array();
$count = 0;
//open file to read contents
$fp = fopen($filename, "r");
//loop to read through csv contents
while ($csvcontents = fgetcsv($fp)) {
$count++;
if ($startrow > 0 && $endrow > 0) {
//delete rows inside startrow and endrow
if ($inner) {
$status = 1;
if ($count >= $startrow && $count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
//delete rows outside startrow and endrow
else {
$status = 2;
if ($count < $startrow || $count > $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
}
else if ($startrow == 0 && $endrow > 0) {
$status = 3;
if ($count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($endrow == 0 && $startrow > 0) {
$status = 4;
if ($count >= $startrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($startrow == 0 && $endrow == 0) {
$status = 5;
} else {
$status = 6;
}
}//end while
if ($status < 5) {
$finalcsvfile = implode("\n", $updatedcsv);
fclose($fp);
$fp = fopen($filename, "w");
fwrite($fp, $finalcsvfile);
}
fclose($fp);
return $status;
} else {
die('File does not exist');
}
}
The function accepts 4 parameters:
filename (string): Path to csv file. Eg: myfile.csv
startRow (int): First row in delete area
endRow (int): Last row in delete area
inner (boolean): decide whether rows deleted are from inner area or outer area
Now Let us consider various cases. I have a csv file with me named ‘test.csv’. Here is the screenshot of the same.
Example 1:
$status = csv_delete_rows('test.csv', 3, 5, true);
will delete the red part of:
Example 2:
$status = csv_delete_rows('test.csv', 3, 5, false);
will delete the red part of:
Example 3:
Like in your situation, if you want to delete the first 100 rows, use this:
$status = csv_delete_rows('test.csv', 0, 100);

Categories