Parse string from array to use in csv - php

Im generating a array that record looks like :
315 =>
array (size=3)
0 => string 'Bangkok ICD' (length=11)
1 => string '[pc_315]' (length=8)
2 => string '45.00;5600.00;677.78;45.00;454.00;;;;'
Next im putting this array in csv using simple mathod:
private function fill_file_data($list)
{
$file = $this->csv_file_path."/tariff_{$this->freight_tariff->id}_matrix.csv";
if(!file_exists($file))
{
file_put_contents($file, "");
}
$file_handler = fopen($file, 'w');
foreach($list as $fields)
{
fputcsv($file_handler, $fields, $this->delimiter, $this->separator);
}
fclose($file_handler);
return;
}
But there is a problem with this part :
2 => string '45.00;5600.00;677.78;45.00;454.00;;;;'
I it is separeted by semicolon but fputcsv treats this as a string. Is there a way to read this part as csv collumns?

I think you should explode your string by ; and add this values as new array elements, for example
$arr = array(
'Bangkok ICD',
'[pc_315]',
'45.00;5600.00;677.78;45.00;454.00;;;;'
);
$new_values = explode(';', $arr[2]);
// now we remove string '45.00;5600.00;677.78;45.00;454.00;;;;'
unset($arr[2]);
$arr = array_merge($arr, $new_values);
After that you can pass this item to your method.

Related

Convert CSV string row with no delimiters into an array

So I'm attempting to explode my string of csv rows into an array and I'm having a difficult time.
Let me lead you through the steps:
var_dump($line); returns an string as this: :string 'TEST Test Test2 Test3
Now, when I have an .txt file, and I call $arr = explode("\t", $line);, the $arr returns an array
array (size=15)
0 => string 'TEST ' (length=11)
1 => string 'Test' (length=4)
2 => string 'Test 2' (length=0)
3 => string 'Test 3' (length=6)
But if I have an .csv file, and I attempt to explode it, I get left with an array string as such:
array (size=1)
0 => string 'TEST Test Test2 Test3'
I tried doing the following but I'm not having much luck: $test = str_getcsv($line, "\t", '', ''); - All the examples for str_getcsv show it like this:
$str = "the,cat,in,the,hat";
$arr = str_getcsv($str);
print_r($arr);
But mine aren't comma separated, but instead all tabbed.
All help would be appreciated.
If you're using a file to get the csv's you should be able to use fgetcsv for this read more here.
$filename = "";
if (($handle = fopen($filename, "r")) !== false) {
while (($line = fgetcsv($handle, 0, "\t")) !== false) {
// $data should be an array of all the items in here.
print_r($line);
}
}

How to match string to an Array to get the value?

I have an array with corresponding value.
Array
(
[0] => BBsma=200
[1] => SMAperiod=300
[2] => SMA1=400
[3] => SMA2=500
[4] => EMAperiod=300
[5] => EMA1=24
[6] => EMA2=8
)
Now I want to match a certain string like for example BBsma that should return 200. Any help?
Got the array using these codes.
$txt = file_get_contents('INDICATORS.txt');
$rows = explode("\n", $txt);
array_shift($rows);
INDICATORS.txt content
BBperiod=100
BBsma=200
SMAperiod=300
SMA1=400
SMA2=500
EMAperiod=300
EMA1=24
EMA2=8
After you explode your text to the lines use this code:
for($i=0;$i<sizeof($rows);$i++)
{
$temp=explode("=",$rows[$i]);
if(sizeof($temp)==2)
{
$arr[$temp[0]]=$temp[1];
}
}
You will have named array in $arr
if you want to cast second part to int, you just change 6-line to this:
$arr[$temp[0]]=intval($temp[1]);
You could iterate over every line of your array and find the value with a regular match.
Code:
$txt = file_get_contents('INDICATORS.txt');
$rows = explode("\n", $txt);
/*
$rows = [
"BBsma=200",
"SMAperiod=300",
"SMA1=400",
"SMA2=500",
"EMAperiod=300",
"EMA1=24",
"EMA2=8",
];
*/
foreach ($rows as $k=>$v) {
if (preg_match("/(BBsma|SMAperiod|EMAperiod)=([0-9]+)/", $v, $matches)) {
echo "found value " . $matches[2] . " for entry " . $matches[1] . " in line " . $k . PHP_EOL;
}
}
Output:
found value 200 for entry BBsma in line 0
found value 300 for entry SMAperiod in line 1
found value 300 for entry EMAperiod in line 4
You can explode by new line as PHP_EOL like this
$col = "BBsma";
$val = "";
foreach(explode(PHP_EOL,$str) as $row){
$cols = explode("=",$row);
if(trim($cols[0]) == $col){
$val = $cols[1];
break;
}
}
echo "Value $col is : $val";
Live Demo
If your going to use the array a few times, it may be easier to read the file into an associative array in the first place...
$rows = [];
$file = "INDICATORS.txt";
$data = file($file, FILE_IGNORE_NEW_LINES);
foreach ( $data as $item ) {
$row = explode("=", $item);
$rows [$row[0]] = $row[1];
}
echo "EMA1 =".$rows['EMA1'];
This doesn't do the array_shift() but not sure why it's used, but easy to add back in.
This outputs...
EMA1 =24
I think that using array filter answers your question the best. It returns an array of strings with status code 200. If you wanted to have better control later on and sort / search through codes. I would recommend using array_walk to create some sort of multi dimensional array. Either solution will work.
<?php
$arr = [
"BBsma=200",
"SMAperiod=300",
"SMA1=400",
"SMA2=500",
"EMAperiod=300",
"EMA1=24",
"EMA2=8",
];
$filtered = array_filter($arr,"filter");
function filter($element) {
return strpos($element,"=200");
}
var_dump($filtered); // Returns array with all matching =200 codes: BBSMA=200
Output:
array (size=1)
0 => string 'BBsma=200' (length=9)
Should you want to do more I would recommend doing something like this:
///////// WALK The array for better control / manipulation
$walked = [];
array_walk($arr, function($item, $key) use (&$walked) {
list($key,$value) = explode("=", $item);
$walked[$key] = $value;
});
var_dump($walked);
This is going to give you an array with the parameter as the key and status code as it's value. I originally posted array_map but quickly realized array walk was a cleaner solution.
array (size=7)
'BBsma' => string '200' (length=3)
'SMAperiod' => string '300' (length=3)
'SMA1' => string '400' (length=3)
'SMA2' => string '500' (length=3)
'EMAperiod' => string '300' (length=3)
'EMA1' => string '24' (length=2)
'EMA2' => string '8' (length=1)
Working with the array becomes a lot easier this way:
echo $walked['BBsma']; // 200
$anything = array("BBsma"=>"200", "SMAperiod"=>"300", "SMA1"=>"400");
echo "the value is " . $anything['BBsma'];
This will return 200

How to get an associative array from a string?

This is the initial string:-
NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n
This is my solution although the "=" in the end of the string does not appear in the array
$env = file_get_contents(base_path() . '/.env');
// Split string on every " " and write into array
$env = preg_split('/\s+/', $env);
//create new array to push data in the foreach
$newArray = array();
foreach($env as $val){
// Split string on every "=" and write into array
$result = preg_split ('/=/', $val);
if($result[0] && $result[1])
{
$newArray[$result[0]] = $result[1];
}
}
print_r($newArray);
This is the result I get:
Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv )
But I need :
Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv= )
You can use the limit parameter of preg_split to make it only split the string once
http://php.net/manual/en/function.preg-split.php
you should change
$result = preg_split ('/=/', $val);
to
$result = preg_split ('/=/', $val, 2);
Hope this helps
$string = 'NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n';
$strXlate = [ 'NAME=' => '"NAME":"' ,
'LOCATION=' => '","LOCATION":"',
'SECRET=' => '","SECRET":"' ,
'\n' => '' ];
$jsonified = '{'.strtr($string, $strXlate).'"}';
$array = json_decode($jsonified, true);
This is based on 1) translation using strtr(), preparing an array in json format and then using a json_decode which blows it up nicely into an array...
Same result, other approach...
You can also use parse_str to parse URL syntax-like strings to name-value pairs.
Based on your example:
$newArray = [];
$str = file_get_contents(base_path() . '/.env');
$env = explode("\n", $str);
array_walk(
$env,
function ($i) use (&$newArray) {
if (!$i) { return; }
$tmp = [];
parse_str($i, $tmp);
$newArray[] = $tmp;
}
);
var_dump($newArray);
Of course, you need to put some sanity check in the function since it can insert some strange stuff in the array like values with empty string keys, and whatnot.

Foreach loop always add first character of string to the array

I am making a function that can help me to cast the string to array, but that strange when the function always add first character to the array. Thank at first and this is code i used in function:
$string = '0:009987;1:12312;2:45231;3:00985;3:10923;4:11253;4:62341;4:01102;4:58710;4:10102;4:87093;4:12034;5:9801;6:1092;6:4305;6:1090;7:450;8:34';
$explodedString = explode(';', $string);
//var_dump($explodedString);
$takeArray = array();
$counti = 0;
foreach($explodedString as $exploded){
$secondExp = explode(':', $exploded);
var_dump($secondExp);
if(isset($takeArray[$secondExp[0]])){
$takeArray[$secondExp[0]][$counti] = $secondExp[1];
}else{
$takeArray[$secondExp[0]] = $secondExp[1];
}
$counti++;
}
var_dump($takeArray);
This is current output of this code:
array (size=9)
0 => string '009987' (length=6)
1 => string '12312' (length=5)
2 => string '45231' (length=5)
3 => string '00981' (length=5)
4 => string '11253 605181' (length=12)
5 => string '9801' (length=4)
6 => string '1092 41' (length=16)
7 => string '450' (length=3)
8 => string '34' (length=2)
Looking into row 4 you will see the string: '605181', this string come from the first character of each value belong to 4. But i need an output array like this:
[0] => {'009987'},
....
[4] => { '11253', '62341', ...., },
....
Please help me.
I'm not sure why you need $counti. All you need to do is, initialize the $takeArray[$n] if it doesn't exists, and push a new value to it. Something like this:
if(!isset($takeArray[$secondExp[0]])) {
// Initialize the array
$takeArray[$secondExp[0]] = array();
}
// Push the new value to the array
$takeArray[$secondExp[0]][] = $secondExp[1];
You only need to do the following :
$takeArray = array();
foreach($explodedString as $exploded) {
$secondExp = explode(':', $exploded);
$takeArray[(int)$secondExp[0]][] = $secondExp[1];
}
$string = '0:009987;1:12312;2:45231;3:00985;3:10923;4:11253;4:62341;4:01102;4:58710;4:10102;4:87093;4:12034;5:9801;6:1092;6:4305;6:1090;7:450;8:34';
$explodedString = explode(';', $string);
$takeArray = array();
foreach($explodedString as $exploded)
{
$secondExp = explode(':', $exploded);
$takeArray[$secondExp[0]][] = $secondExp[1];
}
var_dump($takeArray);

PHP - Explode list variables to array

i have a small problem with the explode function. I have a string like this:
$response:"online,ksksuems,3428939,670605083faeb7750e1afc1010f0f66f8ef0025a,File1.zip
offline,iwksksiw,,, offline,kdlsiwie,,, offline,jdmsmwus,,,
online,uekseks,4023702,37d97c816afdfb10857057d870e74e8774e2bf8a,File2.zip
online,jwksjwa,8860421,20b5e3154653f24963d005cd873917d3cc0a0fe2,File3.rar
online,jsusneus,4912753,9489a47bac4d2a4f7f6810cb37f60924ef48fc48,File4.rar
online,udjdjsis,1177526,5d1da2a1aebae206908ef6d88105f5272ab423e0,File5.zip"
Now I wanted to use the explode function:
list($fileStatus, $fileId, $fileSize, $fileSha1, $fileName) = explode(",", $response);
But I will only get 1 response, if I print the content of $fileStatus. My Question now, how can i get an array for each variable? So that i have "array(ksksuems => online, iwksksiw => offline);" ?
You need to use explode() on your response to put the individual responses into an array and then loop through it to get each other values.
Assuming a the new line character of \n as the separator:
$responses = explode("\n", $response);
foreach ($responses as $resp) {
list($fileStatus, $fileId, $fileSize, $fileSha1, $fileName) = explode(",", $resp);
// do stuff
}
This should work -
$arr = Array();
$lines = explode("\r\n", $response);
//print the exploded lines here.
var_dump($lines);
/*
Expected output -
array
0 => string 'online,ksksuems,3428939,670605083faeb7750e1afc1010f0f66f8ef0025a,File1.zip' (length=74)
1 => string 'offline,iwksksiw,,, offline,kdlsiwie,,, offline,jdmsmwus,,,' (length=59)
2 => string 'online,uekseks,4023702,37d97c816afdfb10857057d870e74e8774e2bf8a,File2.zip' (length=73)
3 => string 'online,jwksjwa,8860421,20b5e3154653f24963d005cd873917d3cc0a0fe2,File3.rar' (length=73)
4 => string 'online,jsusneus,4912753,9489a47bac4d2a4f7f6810cb37f60924ef48fc48,File4.rar' (length=74)
5 => string 'online,udjdjsis,1177526,5d1da2a1aebae206908ef6d88105f5272ab423e0,File5.zip' (length=74)
*/
foreach($lines as $line){
list($fileStatus, $fileId, $fileSize, $fileSha1, $fileName) = explode(",", $line);
$arr[$fileId] = $fileStatus;
}
var_dump($arr);
/*
OUTPUT-
array
'ksksuems' => string 'online' (length=6)
'iwksksiw' => string 'offline' (length=7)
'uekseks' => string 'online' (length=6)
'jwksjwa' => string 'online' (length=6)
'jsusneus' => string 'online' (length=6)
'udjdjsis' => string 'online' (length=6)
*/

Categories