Access php array index issue - php

After use fgetcsv() function I get an array, then I use a foreach() and I get a "simple" associative array like:
Array
(
[ix,radical,variant,simplified,pinyin,english,strokes] => 1,一,,,yi1,one,1
)
Then I try to access any element and I fail:
echo $record['ix'];
Notice: Undefined index: ix
echo next($record); // return nothing!
Maybe is offtopic (not centred in php language) but I'm using some lib (not necessary of course from PHP commenter in http://php.net/manual/es/function.fgetcsv.php)
<?php
require "..\CsvImporter.lib.php";
$importer = new CsvImporter('my_route\\my.csv',true);
while($records = $importer->get())
{
// debug
print_r($records[0]);
exit;
foreach ($records as $record)
{
\\ ..
}
}
And my screen output is
Array ( [ix,radical,variant,simplified,pinyin,english,strokes] => 1,一,,,yi1,one,1 )
My data:
ix,radical,variant,simplified,pinyin,english,strokes
1,一,,,yi1,one,1
2,丨,,,gun3,line,1
3,丶,,,zhu3,dot,1
So how is possible I'm unable to access any key ?

As you posted your data above. Your csv importer giving you each row with comma. So you need to explode it then use however you want to use
Example code \
$i=0;
while($records = $importer->get())
{
if($i>0) //skip first row it is heading
{
$data = explode(',',$records);
print_r($data);
// now `$data[0]` contains `ix` value for your first csv row and so on
}
$i++;
}

I used some lib and the default delimiter was "\t" so something like 'ix,radical,variant,simplified,pinyin,english,strokes' was THE key and '一,,,yi1,one,1' the only value
Now, I see the problem I can do it easy:
$f = 'file.csv';
$separator = ',';
$file = file_get_contents($f);
// bi-dimensional array
$regs = array_map(function($reg){return (explode($separator,$reg));},explode("\n",$file));
Thanks all!

Related

Why does this json_encoded string NOT return the fourth element?

I'm trying to echo a simple json_encoded file.
<?php
$allMessages = file_get_contents("chatmessages.txt");
$allMessagesArr = explode(PHP_EOL, $allMessages);
$newObj = [];
var_dump($allMessagesArr);
foreach ($allMessagesArr as $thisLine) {
// echo($thisLine . "\n");
if (empty($thisLine) ) {
} else {
$thisLineArr = explode("|", $thisLine);
$newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]);
// echo("here comes another one ".$thisLineArr[0] . " : ". $thisLineArr[1]."\n");
}
}
$newObjForFront = json_encode($newObj);
echo($newObjForFront);
chatmessages.txt looks like this
bob|hello
jimmy|second try incoming again
sam|third try
bob|oh damn
I've echoed each individual line within the loop and the fourth element appears. However, when I echo $newObjForFront, it's missing the last element. Any ideas why?
When you create your final array $newObj in
$newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]);
Your using the name as the index to the array. As array indexes have to be unique, this means in fact the last entry overwrites the first one, so your actual output is...
{"bob":"oh damn","jimmy":"second try incoming again","sam":"third try"}
So it is in fact the first message that is missing.
Edit:
If you wanted to just have all of the messages, then you could store them using
$newObj[] = [ "user"=> trim($thisLineArr[0]), "msg" =>trim($thisLineArr[1])];
Which would give you the output as...
[{"user":"bob","msg":"hello"},{"user":"jimmy","msg":"second try incoming again"},{"user":"sam","msg":"third try"},{"user":"bob","msg":"oh damn"}]
$newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]); this line will replace value with the last message of any username. if any username have multiple messages then only last message will be stored in the array.
By creating multidimensional you can store multiple messages with the same username. Check below code that may help you
$newObj[][trim($thisLineArr[0])] = trim($thisLineArr[1]);

Trying to process information from .csv file into PHP

I'm trying to pull information from a .CSV file to process with PHP into a local database.
I have the following code:
<?
$csv = array_map('str_getcsv', file('red.csv'));
echo $csv[1];
?>
The first bit works, if I try to echo the array_map with print_r or var_dump - but I'm not sure how to process it this way.
I'm used to being able to loop through with a for loop where $csv is an array and [0] is the record - but right now the only thing being ECHO'd is Array
I've never worked with array_map's before - and I found the code I am using (Except for the echo obviously) elsewhere online.
How can I loop through the entire array to process each record individually?
The reason Array is being echoed is because str_getcsv returns an array. So $csv is an array with each element inside it being an array of the csv values. If you change it to
<?php
$csv = array_map('str_getcsv', file('red.csv'));
print_r($csv[0]);
?>
You will be able to see the line as an array of each csv item.
You can loop through csv with this:
if (($handle = fopen("your.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, null, ";", '"')) !== FALSE) {
// $data is an array that contains the current row
}
}
note: change the delimiter and escape characters in fgetcsv() according to your csv.
You can travel/iterate over the CSV array using this structure:
foreach( $csv as $row_id => $row_data ) {
foreach( $row_data as $cell_id => $cell_data ) {
// The next will output the same data
echo $cell_data . '\n';
echo $csv[$row_id][$cell_id] . '\n';
}
}
Please follow below code for getting data from csv, looping through each row.
<?php
$csv = array_map('str_getcsv', file('red.csv'));
//print_r($csv[0]);
foreach($csv as $key=>$v)
{
echo $csv[$key][0];//column A/0
echo $csv[$key][1];//column B/1
}
?>

PHP parse CSV by columns

I would like to ask for help with this task: I have CSV for example like this:
column1$column2$column3
123$xyz$321
456$zyx$654
And I would like to parse it by PHP to Arrays by columns / headers -> for example
$column1 = {123,456}
$column2 = {xyz,zyx}
$column3 = {321,654}
Thanks everyone.
Consider the following code and explanations:
$file = file("example.csv"); // read the file to an array
$cols = array();
for ($i=1;$i<count($file);$i++) { // loop over $file,
// starting in the second line
$row = explode('$', $file[$i]); // make an array with explode
for ($j=0;$j<count($row);$j++) // loop over the $row array
array_push($cols["column".$j], $row[$j]);
// push it to the cols array
}
print_r($cols);
What are your curly brackets supposed to do? In PHP an array is formed with [].
Rather than reading the whole file to an array you could as well read each line and push it to the cols array.

How to check if in a folder exists some file in PHP

I'm confusing :S with this script...This script working if there are some file, and I will get the echo like:
|test1.txt|test2.txt|test3.txt|test4.txt
the problem is when doesn't exist any file, the php will get an error:
Warning: asort() expects parameter 1 to be array, null given in htdocs\test\ReadFolder8.php on line 6
Warning: Invalid argument supplied for foreach() in htdocs\test\ReadFolder8.php on line 8
is possible to make a function who look if there are the file, if not, get an echo like "no file found" without error?
<?php
$User = $_GET['User'];
foreach (glob("Myuser/$User/*.txt") as $path) {
$docs[$path] = filectime($path);
} asort($docs); // sort by value, preserving keys
foreach ($docs as $path => $timestamp) {
//print date("d M. Y:|H:i:s |", $timestamp);
print '|'. basename($path) .'' . "" . '';
}
?>
the last thing, I don't understand how works the order for the data creation of file... if I create a new file, the new file will the last of the string...how I can invert the order??
Thank you very much :)
The solution is simple: You need to initialize your variable $docs before you use it to an empty variable like this:
$docs = array(); // <-- create array $docs before use...
foreach (glob("Myuser/$User/*.txt") as $path) {
$docs[$path] = filectime($path);
}
asort($docs); // sort by value, preserving keys
To let the function output an error message instead, if there are no such files, you can simply count the number of array elements using count($docs) and check if it is 0 like this:
if (count($docs) == 0) {
echo "no file found";
}
You can use arsort() instead of asort() to get the latest file as first.

Fill array with contents of csv with php

I am trying to fill a array with a csv so each field is separate part of the array, when i have filled the array and echo it out it quite literally says array for every enter.
I have a feeling that once i sort the csvfull array that the sku might need to be in loop inside the main processing loop to.
$ocuk = fopen("ocuk.csv", "r");
while (($result = fgetcsv($ocuk)) !== false)
{
$csvfull[] = $result;
}
print_r ($csvfull[0][1]);
$sku="$csvfull[1]";
while (($csv = fgetcsv($ocuk)) !== FALSE)
{
if (false === empty(array_intersect($sku, $csv)))
{
code to display the results from csv that match the $sku variable
}
}
What i need it to do is csvfull array to fill with the contents of the csv such i can then call it into the variable sku to do comparison in next part of the code.
EDIT example of what i mean
csv example
data,data2,data3,data4 etc
data10,data20,data30,data40 etc
the array would then be like this
$csvfull=array() would contain the below
array("data","data2","data3","data4");
array("data10","data20","data30","data40");
then when i call csvfull[1] it display data2 then would go onto data 20 etc
$csvfull is a 2-dimensional array. The first dimension is the rows of the CSV, the second dimension is the columns. So $csvfull[1] is an array containing all the values from the second line of the file. To get the SKU, you need to drill down to the appropriate column, e.g.
foreach ($csvfull as $row) {
$sku = $row[1];
// Do something with $sku
}
If you want to get an array of all the SKUs, you can do:
$sku = array();
foreach ($csvfull as $row) {
$sku[] = $row[1];
}
try like this:
<?php
$ocuk = fopen('clientes.csv','r');
$i=0;
while(!feof($ocuk)){
$values = fgetcsv($ocuk);
if(empty($values[1] )){ // any index which is not empty to make sure that you are reading valid row.
continue;}
$csvfull[$i] = $values;
$i++;
}
print_r($csvfull);
.
fclose($ocuk);

Categories