PHP Array Contain string - php

i create a method that will read a file with the application/octet type and here are some of the code.
Raw data :
GTHHS;MEKID Interface;5496;2012-07-20;
NM1;081;IN1;980898989;2001-01-15;Mr;Gaf;Uhkil;Uhkil,Gaf;PRI;Gaf
$contents = file_get_contents($tmp_filename);
$stringContents = explode(";", $contents);
Now it gives me this output :
Array
(
[0] => GTHHS
[1] => MEKID Interface
[2] => 5496
[3] => 2012-07-20
NM1
[4] => 081
[5] => IN1
[6] => 980898989
[7] => 2001-01-15
[8] => Mr
[9] => Gaf
[10] => Uhkil
[11] => Uhkil,Gaf
[12] => PRI
[13] => Gaf
PR1
[14] => 081
[15] => IN1
[16] => 20730089
[17] => 7 The Schooner
[18] => Auhaas
[19] => Huuula Ave
[20] =>
[21] => Kishma
PR2
[22] => 081
[23] => IN1
[24] => 232323233
[25] => 400006
[26] => HGD
[27] => M
[28] => M
[29] => 2007-10-16
[30] => 1976-03-31
);
How can i make the NM1, PR1 as the head of array like this :
Array (
[NM1] = array(
[0] => GTHHS
[1] => MEKID Interface
[2] => 5496
[3] => 2012-07-20
)
);
I am planning also to make the inner array [0]-[3] as json.

If you explode the contents by \n you have each line starting with that identifier. If you then just explode by ; in that line and add it as a sub array, you got it like you want.
This actually looks like a plain old CSV file with your ifentifier in line one. If so, try something like this:
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, ";", "\"", "\n")) !== FALSE)
{
$key = array_shift($row);
$data[$key] = $row;
}
fclose($handle);
}
echo json_encode($data);
http://php.net/manual/en/function.str-getcsv.php

Related

I want all arrays data in one array in php

I want all arrays data in one array not all arrays in one array only the data of all arrays in one array without any other array in php. I have tried to do too many things but still don't work for me.
I also tried
json_encode
with
preg_match
But still don't work for me.
Here is my code
function fetchHashtags($getData){
$body = $getData;
$hashtag_set = [];
$array = explode('#', $body);
foreach ($array as $key => $row) {
$hashtag = [];
if (!empty($row)) {
$hashtag = explode(' ', $row);
$hashtag_set[] = '#' . $hashtag[0];
}
}
print_r($hashtag_set);
}
Output
Array
(
[0] => #Residência
[1] => #architecture
[2] => #casanaserra
[3] => #mountainhouse
[4] => #interiores
[5] => #decoration
[6] => #casanaserra
[7] => #casadecampo
[8] => #construção
[9] => #exterior
[10] => #rustico
[11] => #arpuro
[12] => #home
[13] => #riodejaneiro
[14] => #construir
[15] => #casasincriveis
[16] => #outdoor
[17] => #arquiteto
[18] => #casasincriveis
[19] => #montanhas
[20] => #archdaily
[21] => #architecturelovers
[22] => #arqlovers
[23] => #arqlove
[24] => #homedesign
[25] => #arquiteturaedecoração
)
Array
(
[0] => #We
[1] => #ascaspenvswheaton
)
Array
(
[0] => #شجریان_بشنویم...
[1] => #۰
[2] => #شجریان_بشنویم
[3] => #_
[4] => #شجریانیها
[5] => #همایون_شجریان
[6] => #مژگان_شجریان
[7] => #پرویزمشکاتیان
[8] => #موزیک
[9] => #سهراب_پورناظری
[10] => #محمدرضا_شجریان
[11] => #موزیک_ویدیو
[12] => #ایران
[13] => #ترانه_ماندگار
[14] => #تصنیف
[15] => #آهنگ_ایرانی
[16] => #هنر
[17] => #موسیقی_ایرانی
[18] => #شعروشاعری
[19] => #موسیقی_سنتی_ایران
[20] => #آواز_سنتی
[21] => #قدیمیها
[22] => #دلشدگان
[23] => #دلنشین
[24] => #سینما
[25] => #homayoun_shajarian
[26] => #music
[27] => #mohamadrezashajarian
[28] => #home
[29] => #iran
[30] => #shajarian
)
And one more thing i also want to remove some data that don't look like hashtags.
for example:
Array
(
[0] => #Residência
[1] => architecture // This should be removed
[2] => #casanaserra
[3] => mountainhouse // This also should be removed
[4] => #interiores
)
As you can see from my code you can use array_merge for merge arrays then use array_filter for filter value without # or other rules you need:
$array = [['1', '#2', '3', '#4'], ['5', '#6']];
$flatArray = array_merge(...$array);
$filteredArray = array_filter($flatArray, function($a) {
if (str_contains($a, '#')) {
return $a;
}
});
print_r($filteredArray);
Result:
Array (
[1] => #2
[3] => #4
[5] => #6 )
Reference:
array_merge
array_filter
str_contains
After seeing your code and the context of the situation I changed things:
Instead of use explode i used preg_split for split \n and space;
Delete array_map because you don't need it.
$array = ["
My name is Faraz shaikh i am a php developer and this my #instagram profile.Check out my #merge and my #packages with new #hashtags
#chinese #art #colors #home #harmory #peace #handmade #paintings #etsy
", "
My name is Hunain shaikh i am a php developer and this my #Facebook profile.Check out my #Berge and my #Hackages with new #tags
#english #Kite #colours #me #memory #pee #made #paints #etsafsy
"];
function fetchHashtags($getData) { // This Functions takes out the hashtags from the string and put it in to arrays.
$body = $getData;
$hashtag_set = [];
$array = preg_split('/[\s]+/', $body);
$mapArray = array_map(function($a) {
return str_replace(' ', '', $a);
}, $array);
$filteredArray = array_filter($mapArray, function($a) {
if (str_contains($a, '#')) {
return $a;
}
});
return $filteredArray;
}
$recentNumberOfPosts = 1;
$zeroPost = 0; //Get Post from 0 to recentNumberOfPosts | NOTE: default = 4
$finalArr = [];
while ($zeroPost <= $recentNumberOfPosts) {
// fetchHashtags($hashtagRecent['data'][$zeroPost]['caption']);
$finalArr[] = fetchHashtags($array[$zeroPost]);
$zeroPost++;
}
print_r(array_merge(...$finalArr));
Fiddle

Issue in parsing csv data php | regex replace commas inside of quotes

Anyone share code in php to parse csv data . While am parsing data i got values inside double quotes as separate array so my logic will change . I need to store this data to mysql DB. My sample csv file is below
com,24,2.1.0.5,en,mido,2020-11-01T03:29:32Z,1604201372915,2020-11-01T03:29:32Z,1604201372915,5,,Nice👍👍,2020-11-01T06:34:23Z,1604212463397,"Hi Raju, Thank you so much",497230
com,24,2.1.0.5,en,athene_f,2020-11-01T04:19:52Z,1604204392095,2020-11-01T04:19:52Z,1604204392095,5,,So so,2020-11-01T06:33:58Z,1604212438170,"Hi dev, Thanks",497230
code
$csv_file = 'csv/test.csv';
$file = fopen($csv_file, "r");
fgetcsv($file);
$count=0;
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$getData = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $getData);
$getData = implode(",", $getData);
$getData = '\''.substr($getData , 1, -1).'\'';
$getData =explode(",", $getData);
$exp_array = explode(",", $getData);
$package_name = trim($getData[0]);
$app_version_code = trim($getData[1]);
$app_version_name = trim($getData[2]);
$reviewer_language = trim($getData[3]);
ob_get_clean();
}
expected output
Array
(
[0] => com
[1] => 24
[2] => 2.1.0.5
[3] => en
[4] => mido
[5] => 2020-11-01T03:29:32Z
[6] => 1604201372915
[7] => 2020-11-01T03:29:32Z
[8] => 1604201372915
[9] => 5
[10] =>
[11] => Nice👍👍
[12] => 2020-11-01T06:34:23Z
[13] => 1604212463397
[14] => Hi Raju, Thank you so much
[15] => 497230
)
I just ran this and got the output you indicated you were expecting:
<?php
$file = fopen('input.txt', "r");
while (($data = fgetcsv($file, 10000, ",")) !== FALSE) {
print_r($data);
}
Here's input.txt:
com,24,2.1.0.5,en,mido,2020-11-01T03:29:32Z,1604201372915,2020-11-01T03:29:32Z,1604201372915,5,,Nice👍👍,2020-11-01T06:34:23Z,1604212463397,"Hi Raju, Thank you so much",497230
com,24,2.1.0.5,en,athene_f,2020-11-01T04:19:52Z,1604204392095,2020-11-01T04:19:52Z,1604204392095,5,,So so,2020-11-01T06:33:58Z,1604212438170,"Hi dev, Thanks",497230
And here's the output:
Array
(
[0] => com
[1] => 24
[2] => 2.1.0.5
[3] => en
[4] => mido
[5] => 2020-11-01T03:29:32Z
[6] => 1604201372915
[7] => 2020-11-01T03:29:32Z
[8] => 1604201372915
[9] => 5
[10] =>
[11] => Nice👍👍
[12] => 2020-11-01T06:34:23Z
[13] => 1604212463397
[14] => Hi Raju, Thank you so much
[15] => 497230
)
Array
(
[0] => com
[1] => 24
[2] => 2.1.0.5
[3] => en
[4] => athene_f
[5] => 2020-11-01T04:19:52Z
[6] => 1604204392095
[7] => 2020-11-01T04:19:52Z
[8] => 1604204392095
[9] => 5
[10] =>
[11] => So so
[12] => 2020-11-01T06:33:58Z
[13] => 1604212438170
[14] => Hi dev, Thanks
[15] => 497230
)
If you are not getting the expected output, one other thing to check is the file encoding on your CSV file. It could be that your PHP script is expecting your file to be utf-8 encoded, but your file is using another encoding. There are lots of resources online for detecting file encoding and converting using PHP.
These 2 lines are 100% incorrect...
$getData =explode(",", $getData);
$exp_array = explode(",", $getData);
givn, that $getData contains a string, after explode() it will be an array (reassigned to $getData).
On the next line, this array is tried to be exploded again, but this will fail and give you warnings or errors.
Turn up error reporting level and display all errors on screen during development.

Finding MAX value of raw CSV data for specific column in PHP

Using cURL:
$url = $some_site;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
where the '$output' variable contains the following 7 columns (# of rows will vary):
1,a,6045,6168,6731,6847,522800
2,b,7847,8124,7645,7716,614400
3,c,7288,7633,7150,7442,801800
4,d,5546,5791,5460,5581,554200
5,e,4579,4679,4359,4572,557400
etc ...
As you can see, in the 4th column, the numbers are:
6168
8124
7633
5791
4679
And the highest number is: 8124
I am trying to figure out how to parse the '$output' variable so I can evaluate all the numbers in the 4th column to determine the high.
I have tried:
$csv = array_map('str_getcsv', $output);
echo max($csv[4]);
But nothing is returned
If you output your $csv value you will see that it is array with structure like:
...
[2] => Array
(
[0] => 3
[1] => c
[2] => 7288
[3] => 7633
[4] => 7150
[5] => 7442
[6] => 801800
)
[3] => Array
(
[0] => 4
[1] => d
[2] => 5546
[3] => 5791
[4] => 5460
[5] => 5581
[6] => 554200
)
[4] => Array
(
[0] => 5
[1] => e
[2] => 4579
[3] => 4679
[4] => 4359
[5] => 4572
[6] => 557400
)
....
So your $csv[4] is not a list of values from column 4. It's the 5th element of your array. So you need to go further, either with a simple foreach:
$max = 0;
foreach ($csv as $row) {
// use index `3` because numeration starts with `0`
if ($max < $row[3]) {
$max = $row[3];
}
}
Or with array_column (since php5.5):
// take all values witn index `3` and find max
echo max(array_column($csv, 3));
In both cases it is 8124
It's because str_getcsv not following standards, and from output You have a "broken array"... I suppose that it may look like this:
Array
(
[0] => 1
[1] => a
[2] => 6045
[3] => 6168
[4] => 6731
[5] => 6847
[6] => 522800
2
[7] => b
[8] => 7847
[9] => 8124
[10] => 7645
[11] => 7716
[12] => 614400
3
[13] => c
[14] => 7288
[15] => 7633
[16] => 7150
[17] => 7442
[18] => 801800
4
[19] => d
[20] => 5546
[21] => 5791
[22] => 5460
[23] => 5581
[24] => 554200
5
[25] => e
[26] => 4579
[27] => 4679
[28] => 4359
[29] => 4572
[30] => 557400
)
http://sandbox.onlinephpfunctions.com/code/b5834d98eda11b1726adc9ef1b7592f9ba32242c
You can do it like this:
<?php
// $csv is just a string ... output from Your curl will be same I think
$csv = <<<EOT
1,a,6045,6168,6731,6847,522800
2,b,7847,8124,7645,7716,614400
3,c,7288,7633,7150,7442,801800
4,d,5546,5791,5460,5581,554200
5,e,4579,4679,4359,4572,557400
EOT;
function csv2array($csv) {
$csv = str_getcsv($csv, PHP_EOL);
return array_map('str_getcsv', $csv);
}
function findMaxInColumn($array, $column = 3) {
return max(array_column($array, $column));
}
$parsedCsv = csv2array($csv);
print_r(findMaxInColumn($parsedCsv));
http://sandbox.onlinephpfunctions.com/code/82020f0d85acf8d6b15b5e7fd78a8d1a80618ff2

scandir() scan by increasing number

I want to scan a directory and add all the file-names to an array in ascending order (numeric, no letters). What appears to be happening is scandir() is sorting them by highest value of the first number and not the whole number. I need to take into account missing text files, so if 9.txt was missing, 10.txt would take its place (no empty spot in array).
Here is the code:
<?php
$array=array();
$int = 1;
$holder=scandir("/postexamples/");
krsort($holder);
foreach($holder as $x)
{
if(!is_dir($x)){
$array[$int]=$x;
$int++;
}
}
echo PHP_EOL . PHP_EOL . "Final array: " , PHP_EOL;
print_r($array);
?>
Which outputs the array:
Array ( [1] => 9.txt [2] => 8.txt [3] => 7.txt [4] => 6.txt [5] => 5.txt [6] => 4.txt [7] => 3.txt [8] => 20.txt [9] => 2.txt [10] => 19.txt [11] => 18.txt [12] => 17.txt [13] => 16.txt [14] => 15.txt [15] => 14.txt [16] => 13.txt [17] => 12.txt [18] => 11.txt [19] => 10.txt [20] => 1.txt )
Is there a better (and preferably working) way to do this? I need it to be like [1] => 1.txt [2] => 2.txt
EDIT:
I need the array to appear like this:
Array ( [1] => 1.txt [2] => 2.txt [3] => 3.txt [4] => 4.txt [5] => 5.txt [6] => 6.txt [7] => 7.txt [8] => 8.txt [9] => 9.txt [10] => 10.txt [11] => 11.txt [12] => 12.txt [13] => 13.txt [14] => 14.txt [15] => 15.txt [16] => 16.txt [17] => 17.txt [18] => 18.txt [19] => 19.txt [20] => 20.txt )
And if one file (for example, 17.txt) was missing, it would look like this:
Array ( [1] => 1.txt [2] => 2.txt [3] => 3.txt [4] => 4.txt [5] => 5.txt [6] => 6.txt [7] => 7.txt [8] => 8.txt [9] => 9.txt [10] => 10.txt [11] => 11.txt [12] => 12.txt [13] => 13.txt [14] => 14.txt [15] => 15.txt [16] => 16.txt [17] => 18.txt [18] => 19.txt [19] => 20.txt )
You need to do a natural sort to get the files in the correct order (20.txt, 10.txt, 2.txt, 1.txt). The function for doing this is natsort.
$sortPath = 'postexamples/';
$files = array();
foreach (scandir($sortPath) as $file) {
if (is_file("$sortPath/$file")) {
$files[] = $file;
}
}
echo PHP_EOL . PHP_EOL . "Final array: " , PHP_EOL;
natsort($files);
$files = array_values($files); // re-key array
print_r($files);
Result
Final array:
Array
(
[0] => 1.txt
[1] => 2.txt
[2] => 4.txt
[3] => 10.txt
[4] => 20.txt
)
Id do it like this.
$files = array_diff(scandir("/postexamples/"), array('.', '..' ));
$array = array();
foreach($files as $file){
if(!is_dir($file)){
$array[]=$file;
}
}
sort($array, SORT_NUMERIC);
You may have to use usort, if it doesn't do the numbers right. Also if you are on php >= 5.4 you may be able to use,
scandir("/postexamples/", SCANDIR_SORT_ASCENDING );
But I haven't tried it. Using sort with numeric flag ( don't forget it's just an array like any other )
$a = Array ( '9.txt', '8.txt', '7.txt', '6.txt', '10.txt', '1.txt');
echo "<pre>";
var_export($a);
echo "<br>";
sort($a, SORT_NUMERIC);
var_export($a);
Result
array (
0 => '9.txt',
1 => '8.txt',
2 => '7.txt',
3 => '6.txt',
4 => '10.txt',
5 => '1.txt',
)
array (
0 => '1.txt',
1 => '6.txt',
2 => '7.txt',
3 => '8.txt',
4 => '9.txt',
5 => '10.txt',
)
So essentially sort($a, SORT_NUMERIC);
Try this ,i hope this will help you:
$ar=array();
$g=scandir("/postexamples/");
krsort($g)
foreach($g as $x)
{
if(is_dir($x))$ar[$x]=scandir($x);
else $ar[]=$x;
}
print_r(sort($ar));

Export data to CSV file using PHP - output is empty

I thought it will be easy task, but simple I'm not able to output data from an array to CSV file (saved on a server).
Code for that part looks like:
$fp = fopen('missing-skus.csv', 'w');
foreach ($missing_array as $lines) {
fputcsv($fp, $lines);
}
fclose($fp);
$missing_array looks like:
Array
(
[0] => 5804
[1] => 5803
[2] => 5802
[3] => 5801
[4] => 5800
[5] => 5799
[6] => 5798
[7] => 5797
[8] => 5796
[9] => 5795
[10] => 5794
[11] => 5793
[12] => 5792
[13] => 5791
[14] => 5790
[15] => 5789
[16] => 5788
[17] => 5787
[18] => 5786
[19] => 5785
[20] => 5784
[21] => 5783
[22] => 5782
[23] => 5781
[24] => 5780
[25] => 5779
)
No matter what, file is always blank. Any clue what I have missed?
The second argument to fputcsv is an array of fields. You are passing a string or integer.
If you want one line with the array values as fields, in CSV fashion, then just:
$fp = fopen('missing-skus.csv', 'w');
fputcsv($fp, $missing_array);
If you just want each array value on one line then no need for fputcsv:
file_put_contents('missing-skus.csv', implode("\n", $missing_array));

Categories