Declaring different variables in foreach loop - php

I know the title of my question may be confusing, but I'm not quite sure how to explain what I'm trying to do concisely.
I am trying to loop through an array of CSVs and load the data into variables with differing names. In my example below, instead of $foo_data it would be $MSFT_data, $AAPL_data, and $FB_data in each loop through the $stocks array.
$stocks = array($msft, $aapl, $fb);
foreach ($stocks as $stock) {
$fh = fopen($stock, 'r');
$header = fgetcsv($fh);
$foo_data = array();
while ($line = fgetcsv($fh)) {
$foo_data[] = array_combine($header, $line);
}
fclose($fh);
}
Please let me know if you need more information.

There are two problems. The first is that you cannot get the variable name, so the script has no way to know that there is an $msft, $aapl, $fb, so you need to pass the name along with the array. The second is that you need variable variables.
Try
$stocks = array('MSFT' => $msft, 'AAPL' => $aapl, 'FB' => $fb);
foreach ($stocks as $key=>$stock) {
$fh = fopen($stock, 'r');
$header = fgetcsv($fh);
$varname = $key . '_data';
$$varname = array(); //the double $$ will set the var content as variable ($MSFT_data)
while ($line = fgetcsv($fh)) {
${$varname}[] = array_combine($header, $line);
//the {} are needed to let PHP know that $varname is the name of the variable and not $varname[].
}
fclose($fh);
}

$MSFT_data = $foo_data[0];
$AAPL_data = $foo_data[1];
$FB_data = $foo_data[2];
How does that work for you?

Related

Create key-value pair from csv php

I have a csv file like below
tl_blade_thickness,tl_blade
test1,test1
test2,test2
test3,test3
test4,test4
test5,test5
test6,test6
test7,test7
test8,test8
test9,test9
I'm trying to create a key value pair array like below.
["tl_blade_thickness"=>["test1","test2","test3",...],tl_blade=>["test1","test2","test3",...]]
I tried like this below.
$content = fopen("csv.csv", "r");
$all_rows = array();
$header = fgetcsv($content);
while ($row = fgetcsv($content)) {
$all_rows[] = array_combine($header, $row);
}
Use the first line of the file to create the keys of the array. Then push each field of the remaining lines into the corresponding element keys.
$content = fopen("csv.csv", "r");
$headers = fgetcsv($content);
$all_rows = array_fill_keys($headers, []);
while ($row = fgetcsv($content)) {
foreach ($headers as $i => $name) {
$all_rows[$name][] = $row[$i];
}
}

Import variables in file into array

Basically, I have multiple files containing loads of PHP variables, and i'm trying to create a way to read them in to a subarray for each file with each variable being in the array.
<?php
$data = Array();
$getData = glob('siteData/*.vars.php', GLOB_BRACE);
foreach($getData as $tempData) {
$dataKey = str_replace(".vars.php", "", str_replace("siteData/", "", $tempData));
$data[$dataKey] = Array();
//foreach varaible in file
//$data[$dataKey][$varaibleName] = $variable
}
?>
The bit commented out is the bit I need help with as I have no idea how to do it.
Please help, TIA.
After a bit of help, the answering code is as follows:
<?php
$data = Array();
$getData = glob('siteData/*.vars.php', GLOB_BRACE);
foreach($getData as $tempData) {
$dataKey = str_replace(".vars.php", "", str_replace("siteData/", "", $tempData));
$data[$dataKey] = Array();
$dataFile = file_get_contents($tempData);
preg_match_all('/\$[A-Za-z0-9-_]+\s?=\s?["\'].+["\'];/', $dataFile, $dataVars);
$dataVars = $dataVars[0];
foreach($dataVars as $variable) {
$variable = explode("=", $variable);
$varaibleName = ltrim(trim($variable[0]), "$");
$variable = trim(trim(rtrim(trim($variable[1]), ";"), "'"), '"');
$data[$dataKey][$varaibleName] = $variable;
}
}
print_r($data);
?>

PHP read in specific csv file column as an array

I am new to PHP and would like to be able to read in a csv file which has two columns, one is the number (kind of like a ID) then the other holds a integer value. I have looked up the fgetcsv function but I have not been able to find a way to read a specific column from the csv file.
I would like to get all the values from the second column only, without the heading.
Any way of doing this?
This is what I have so far:
$file = fopen('data.csv', 'r');
$line = fgetcsv($file);
And this is some sample data from the csv file:
ID,Value
1,243.00
2,243.00
3,243.00
4,243.00
5,123.11
6,243.00
7,180.00
8,55.00
9,243.00
Any help would be appreciated.
Thanks.
fgetcsv() only reads a single line of the file at a time. You'll have to read the file in a loop to get it all:
$data = array();
while($row = fgetcsv($file)) {
$data[] = $row;
}
The heading you can skip by doing an fgetcsv once outside the loop, to read/trash the header values. And if you only want the second column, you can do:
$data[] = $row[1];
However, since you've got data in there, maybe it might be useful to keep it, plus key your new array with the ID values in the csv, so you could also have:
$data[$row[0]] = $row[1];
and then your nice shiny new array will pretty much exactly match what's in the csv, but as an array keyed by the ID field.
$csv = array_map("str_getcsv", file("data.csv", "r"));
$header = array_shift($csv);
// Seperate the header from data
$col = array_search("Value", $header);
foreach ($csv as $row) {
$array[] = $row[$col];
}
// Iterate through data set, creating array from Value column
$header = fgetcsv($h);
$rows = array();
while ($row = fgetcsv($h)) {
$rows []= array_combine($header, $row);
}
$fp = fopen($filePath, "r+");
$header = fgetcsv($fp);
while ($members = fgetcsv($fp)) {
$i = 0;
foreach ($members as $mem) {
$membersArray[ $i ][ ] = $mem;
$i++;
}
}
$newArray = array_combine($header, array_map("array_filter",$membersArray));
You can also use this class http://code.google.com/p/php-csv-parser/
<?php
require_once 'File/CSV/DataSource.php';
$csv = new File_CSV_DataSource;
$csv->load('data.csv');
var_export($csv->connect());
?>

php string name as variable in array

how take string from array define as new array,
how to code in php
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "1";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
I want to take string from $column array define as new array.
how to code it?
or if my question is stupid , my please to have suggestion.
thank you.
Answer I made on your previous question:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $column_name => $column_value) {
$temp_array[$column_name][$i] = $column_value;
}
$i++;
}
foreach ($temp_array as $name => $answer) {
$$name = $answer;
}
}
I can't see why you'd want to model your data like this, you're asking for a world of hurt in terms of debugging. There are "variable variables" you could use to define this, or build global variables dynamically using $GLOBALS:
$somevar = "hello"
$$somevar[0] = "first index"; // creates $hello[0]
$GLOBALS[$somevar][0] = "first index"; // creates $hello[0] in global scope
try
$array = array();
foreach ($results as $r){
foreach ($column as $col ){
$array[$col][] = $r[$col];
}
}
extract ($array);
or you can simply do this
$id = array();
$name = array();
$value = array();
foreach ( $results as $r ){
$id[] = $r['id']; // or $r[0];
$name[] = $r['name'];
$value[] = $r['value'];
}
Hope this is what you asked
This is pretty dangerous, as it may overwrite variables you consider safe in your code. What you're looking for is extract:
$result = array();
while ($row = mysql_fetch_array($result))
foreach ($column as $i => $c)
$result[$c][] = $row[$i];
extract($result);
So, if $result was array( 'a' => array(1,2), 'b' => array(3,4)), the last line defines variables $a = array(1,2) and $b = array(3,4).
You cannot use variable variables right on for this, and you shouldn't anyway. But this is how you could do it:
foreach (mysql_fetch_something() as $row) {
foreach ($row as $key=>$value) {
$results[$key][] = $value;
}
}
extract($results);
Ideally you would skip the extract, and use $results['id'][1] etc. But if you only extract() the nested array in subfunctions, then the local variable scope pollution is acceptable.
There is no need for arrays or using $_GLOBALS, i believe the best way to create variables named based on another variable value is using curly brackets:
$variable_name="value";
${$variable_name}="3";
echo $value;
//Outputs 3
If you are more specific on what is the array you receive i can give a more complete solution, although i must warn you that i have never had to use such method and it's probably a sign of a bad idea.
If you want to learn more about this, here is a useful link:
http://www.reddit.com/r/programming/comments/dst56/today_i_learned_about_php_variable_variables/

open file with raw csv data, explode array and subarray, change line, and pack it back up and save, in PHP

My goal here is to open temp.php, explode by ### (line terminator), then by %% (field terminator). Change a specific field, on a specific line, then implode everything back together and save it.
There are a couple variables at play here:
row = the target row number
target = the target field/column number
nfv = the info that i want to place into the target field
Im using the counter $i to count until i get to the desired row. Then counter $j to count til i get to my desired field/target. So far this gives me an error for invalid implode arguments, or doesn't save any data at all. Im sure there are a couple things wrong, but i am frustrated and lost.
<?
$row = $_GET['row'];
$nfv = $_GET['nfv'];
$target = $_GET['target'];
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
$j = 0;
foreach ( $csvpre AS $key => $value){
$i++;
if($i == $row){
$info = explode("%%", $value);
foreach ( $info as $key => $value ){
$j++;
if($j == "$target"){
$value = $nfv;
}
}
$csvpre[$key] = implode("%%", $info);
}
}
$save = implode("###", $csvpre);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
header("Location: data.php");
?>
If someone can tell what is wrong with this, please be detailed so i can learn why its not working.
Here is some sample csv data for testing
1%%4%%Team%%40%%75###2%%4%%Individual%%15%%35###3%%4%%Stunt Group%%50%%150###4%%4%%Coed Partner Stunt%%50%%150###5%%4%%Mascot%%15%%35###6%%8%%Team%%40%%75###7%%8%%Stunt Group%%50%%150###8%%8%%Coed Partner Stunt%%50%%150###9%%3%%Team%%40%%75###10%%1%%Team%%40%%75###11%%1%%Solo%%15%%35###12%%1%%Duet%%50%%150###13%%2%%Team%%50%%50###14%%2%%Solo%%15%%35###15%%2%%Duet%%50%%150###16%%8%%Individual%%15%%35###
The following should work. This also eliminates a lot of unnecessary looping
<?php
$row = $_GET['row'];
$nfv = $_GET['nfv'];
$target = $_GET['target'];
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
//removed i and j. unnecessary.
//checks if the row exists. simple precaution
if (isset($csvpre[$row]))
{
//temporary variable, $target_row. just for readability.
$target_row = $csvpre[$row];
$info = explode("%%", $target_row);
//check if the target field exists. just another precaution.
if (isset($info[$target]))
{
$info[$target] = $nfv;
}
//same as yours. just pack it back together.
$csvpre[$row] = implode("%%", $info);
}
$save = implode("###", $csvpre);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
header("Location: data.php");
?>
The looping you were doing was removed as the row were numerically indexed already anyways. Accessing the array element directly is much faster than looping through the elements until you find what you want.

Categories