Using str_replace function to replace multiple string of an array - php

I have a multidimensional array $arrResult1 imported from CSV file, I want to replace the multiple values in that array with different values. I have tried str_replace and it works for single replacement.
<?php
$File = 'charge1.csv';
$arrResult = array();
$handle = fopen($File,"r");
if(empty($handle) == false){
while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){
$arrResult[] = $data;
}
fclose($handle);
}
$file = 'ActualCharge.csv';
$arrResult1 = array();
$handle = fopen($file,"r");
if(empty($handle) == false){
while(($values = fgetcsv($handle, 1000, ",")) !== FALSE){
$arrResult1[] = $values;
}
fclose($handle);
}
$newArray = array();
foreach($arrResult1 as $inner_array) {
$newArray[] = str_replace("$11.16","$14.00", $inner_array);
}
var_dump($newArray[6]);
But when I try to replace more values like this
$newArray[] = str_replace(array("$11.16","$14.00"),array("$12.16","$15.00"), $inner_array);
It does not work. I have total 16 values that need to be replaced. Can you please help and let me know what I am doing wrong here or if there is any other way to solve this. TIA
here are the links to both csv files
https://drive.google.com/open?id=15JXhljASiDaZAyF0I6vC5_vfvFWH5Ylo
https://drive.google.com/open?id=1XzbzE39sCVVi4Ox1uj36g0smZJ4X4kCv

Related

PHP: Remove a row from a CSV if ID occurs multiple times and a column has a specific value

I have data as below in a CSV file. The green lines are what I'd like to keep.
Basically if someone has a single line, I want to keep it.
If they have multiple lines, I want to remove any where the 3rd column is A - Fully Fit.
After running through the whole file, I then want to save it over the original.
I tried writing the code but not sure if it's a Friday but the logic is escaping me at the moment.
There could be just a single line or there could be dozens. So if an ID has 1000 rows, I would just want to delete the rows for that ID where the 4th column is "A - Fully Fit"
UPDATE
This code works but not sure if it's the most optimal
// DECLARE ARRAYS
$a = Array();
$b = Array();
$c = Array();
// LOOP THROUGH FILE AND COLLECT DUPLICATES
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($line = fgetcsv($handle, 4096, ",")) !== FALSE) {
$a[$line[1]][] = 'SHAKKA';
}
foreach ($a as $k=>$v) {
if (count($v)>1) {
$b[] = $k;
}
}
}
// IF A DUPLICATE THEN REMOVE ROWS THAT ARE 'A - Fully Fit'
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($golly = fgetcsv($handle, 4096, ",")) !== FALSE) {
if (in_array($golly[1],$b) && $golly[3] == 'A - Fully Fit') {
}
else {
$c[] = $golly;
}
}
}
fclose($handle);
// WRITE THE FILE
$fp = fopen($filename, 'wa+');
foreach ($c as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
<?php
if (($handle = fopen($filename, "r")) !== FALSE) {
$new_rows = [];
$hash_ids = [];
while (($line = fgetcsv($handle, 4096, ",")) !== FALSE) {
if($line[3] === 'A - Fully Fit'){
if(isset($hash_ids[$line[1]])) continue;
$hash_ids[$line[1]] = true;
}
$new_rows[] = $line;
}
fclose($handle);
// WRITE TO THE FILE
$fp = fopen($filename, 'wa+');
foreach ($new_rows as $current_row) {
fputcsv($fp,$current_row);
}
fclose($fp);
}
In the above code, we maintain a hash(associative array) for each ID. If we have already come across with an ID with A - Fully Fit, then we skip the row, else we add it to the list.

Convert a CSV file into JSON [BUG]

I would like to create a JSON file with my CSV file.
But I get an error with the function array_combine.
How could i fix that please?
Here is the code:
function csvtojson($file,$delimiter)
{
if (($handle = fopen($file, "r")) === false)
{
die("can't open the file.");
}
$csv_headers = fgetcsv($handle, 4000, $delimiter);
$csv_json = array();
while ($row = fgetcsv($handle, 4000, $delimiter))
{
$csv_json[] = array_combine($csv_headers, $row);
}
fclose($handle);
return json_encode($csv_json);}
Here is the error:
Warning: array_combine(): Both parameters should have an equal number
of elements in /var/www/inae-obs/app/controllers/csvToJson.php on line
15
You can use a custom array_combine method to overcome this:
<?php
function array_combine_custom($keys, $values){
$combined = [];
$keys_values = array_values($keys);
$values_values = array_values($keys);
foreach($keys_values as $index => $key){
$combined[$key] = isset($values_values[$index]) ? $values_values[$index] : null;
}
return $combined;
}
if the keys and values are in order and you are OK with ignoring the rest.

fgetcsv convert array to string with double quote enclosure

I am getting data from a csv as an array using the fgetcsv function. I want to convert the array into a string, so I have used the implode function.
CODE:
if (($handle = fopen("storelocations.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$datafinal = implode(",",$data);
echo $datafinal;
}
fclose($handle);
}
I am getting the result string say as Ter Aar, Netherlands,4.7159509,52.164688,,211316. But I would like each entry to be enclosed by double quotes. How can I do that?
Expected result: `"Ter Aar", "Netherlands","4.7159509","52.164688","","211316"
My approach #1 -
I passed the " as enclosure following the documentation but it is not working.
if (($handle = fopen("../storelocations.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",", '"')) !== FALSE) {
$datafinal = implode(",",$data);
echo $datafinal;
}
fclose($handle);
}
My approach #2 -
function convert( $str ) {
return '"'.$str.'"';
}
if (($handle = fopen("../storelocations.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",", '"')) !== FALSE) {
//$datafinal = array_map( convert, $data );
$datafinal = implode(",",$data);
echo $datafinal;
//var_dump($data);
}
fclose($handle);
}
This returns a string as "Ter Aar", "Netherlands","4.7159509","52.164688","","""211316".
As you can see the item following the blank data gets three quotes in the beginning.
You can do it as follows
// PHP 5.3 and later
echo $datafinal = implode(",",array_filter($data, function($value) { return $value !== ''; }));
This will help you sure
Thanks
Hope! It will help you
Try following code to read csv file and get data as multi-dimentional array
$csv_data = array_map('str_getcsv', file('../storelocations.csv'));
foreach ($csv_data as $key => $value)
{
var_dump($value); // print each row of csv
var_dump($value[0]) // print first column of each row
}

PHP changing the index of multidimentional array to value of variable

Pretty new to PHP. I have a csv feed that i am trying to display every line of in the right place. The feed is loaded into a multidimentional array and I can echo out specific places like this.
echo $readcsv[0][2]
But I am trying to use the value of the variable $row in stead of the first number while doing a while loop.
Something like:
echo $readcsv[$row][2]
I have tried next(), str_replace() and strtr() but none of them seems to work while the loop is running.
$row = 1;
$readcsv = array();
if (($handle = fopen("file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$num = count($data);
echo $readcsv[$row][2];
$row++;
for ($c=0; $c < $num; $c++) {
}
$mycsvfile[] = $data;
}
fclose($handle);
}
CSV file:
title;image_link;link;empty;price;
1;back.gif;http://link.com;;19.95;
2;back.gif;http://link.com;;19.95;
3;back.gif;http://link.com;;19.95;
4;back.gif;http://link.com;;19.95;
5;back.gif;http://link.com;;19.95;
I am not quite sure from your code and question exactly what you are trying to do, but maybe its something like this
if (($handle = fopen("file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
// you load the line into $data and its a one dimentional array
// occurance 2 is the `link` (http://link.com) if that what you want to echo
echo $data[2];
// as you have a loop, maybe you were trying to
// echo each fields from the csv so you can do that like this
foreach ($data as $idx => $value) {
echo "Column $idx = $value";
}
$mycsvfile[] = $data;
}
fclose($handle);
}

Edit first line CSV with PHP

I want to edit the first line (column titles) of an CSV file. Only one problem, the script I have is replacing everything. I've tried to search for a solution, but no luck.
Script:
<?php if(isset($_FILES["file"]["tmp_name"])){
$newCsvData = array();
if (($handle = fopen("".$_FILES["file"]["tmp_name"]."", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $base = array("EAN","article","status");
$replacements = array(1=> "SKU");
$basket = array_replace($base, $replacements);
$newCsvData[] = $basket;
}
fclose($handle);
}
$handle = fopen("export/".$_FILES["file"]["name"]."", "w");
foreach ($newCsvData as $line) {
fputcsv($handle, $line);
}
fclose($handle); } else{ echo" ";} ?>
Does someone know what I'm doing wrong?
You should try:
$first = true;
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
$base = array("EAN", "article", "status");
$replacements = array(1 => "SKU");
if($first){
$data = array_replace($base, $replacements);
$first = false;
}
$newCsvData[] = $data;
}
$first is a flag to detect just first row and replacing $data array values with titles array. Then you should push $data to $newCsvData. So only first row will replace by new values and other rows will remain as same data.

Categories