Need two dimensional array for 2 column CSV from 2 strings - php

I am working on a project to create 2 column CSV using PHP and i have the data stored as strings in 2 different variables . Consider below example of what i have and what i need further. Thank you in advance.
I have below 2 variables and data stored inside them. (data is separated by comma)
$title = title1,title2,title3,title4,title5..and so on
$values = value1,value2,value3,value4,value5..and so on
I need this array pattern like this
$multi_array = array
(
array(title1,value1),
array(title2,value2),
array(title3,value3),
);
I will then use the below code to generate 2 column CSV via PHP
// open the file "demosaved.csv" for writing
$file = fopen('demosaved.csv', 'w');
// save the column headers
fputcsv($file, array('Column 1', 'Column 2'));
// save each row of the data
foreach ($multi_array as $row)
{
fputcsv($file, $row);
}
// Close the file
fclose($file);

Since the values are comma separated strings, explode them into arrays:
$title = explode(",", $title);
$values = explode(",", $values);
Then you can just use the key to match up the values from each array (assuming that they are the same length):
foreach ($values as $key => $val)
{
fputcsv($file, [$title[$key], $val]);
}
Or combine them:
$multi_array = array_combine($title, $value);
foreach ($multi_array as $title => $value)
{
fputcsv($file, [$title, $value]);
}
If you're on an old version of PHP you'll need array() instead of [ ].
From the OP, since there many be duplicates in the string that would be duplicate keys: "use the below code to perform the same job and even keep the duplicate keys. PHP array_combine removes the duplicate array entries but below code keeps all entries:"
$arrKeys = array('str', 'str', 'otherStr');
$arrVals = array('1.22', '1.99', '5.17');
function foo($key, $val) {
return array($key=>$val);
}
$arrResult = array_map('foo', $arrKeys, $arrVals);
print_r($arrResult);

Related

php var with multiple assoc arrays, get values one array at a time

Originally I was taking an uploaded .csv file and iterating through the values one row at a time.. with the below while loop.
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
var_dump($data);
$importIt = $repo->impThreeCSV($which, $data);
}
I have redone the .csv upload functionality to now be a web form where I send json to the PHP file on a 'save button'. I now have a variable with multiple associative arrays in it..
$fd = json_decode($df, true);
var_dump($fd);
For instance the dump above contains multiple arrays such as below: i.e. (~300 similar arrays as below).
array (size=806)
0 =>
array (size=18)
'ATM_ID' => string 'AFF-MIL-TWR' (length=11)
'FAC_IDENT' => string 'AFF' (length=3)
'LG_NAME' => string 'BLACH BLAH ACADEMY' (length=20)
'BASIC_TP' => string 'MIL-TWR' (length=7)
.................
How can I iterate through the VALUES only in these arrays, one at a
time in the same fashion as my original while loop.. (this would be
ideal so I don't have to redo the whole back-end).
I am having issues handling the multiple arrays and getting the
values only out..
I have tried the below two attempts, I just get 'arrayarrayarray' or
similar in var_dump. Do I need to break out each array into it's
own var? What am I doing wrong here? Do I need to run a count on how
many arrays consist in my var?
$fd = json_decode($df, true);
var_dump($fd);
$data = array_values($fd);
foreach ($data as $array_key) {
echo $array_key;
}
$array_keys = array_keys($fd);
foreach ($array_keys as $array_key) {
echo $array_key;
}
P.S. No, I can't use pandas, I wish.
Assuming you want to process the data in the same way as your original piece of code, you would just use something like:
foreach ($fd as $data) {
$importIt = $repo->impThreeCSV($which, array_values($data));
}
Note I've used array_values to convert $data from an associative array to a numerically indexed one, i.e. the same format as fgetcsv returns. This may - dependent on your $repo->impThreeCSV code - not be necessary.
You need to do a foreach to loop through each array, and then do another foreach to loop through every value of the array you're looping through.
$decodedJson = [
[
'ATM_ID' => 'AFF-MIL-TWR 1',
'FAC_IDENT' => 'AFF',
'LG_NAME' => 'BLACH BLAH ACADEMY',
'BASIC_TP' => 'MIL-TWR',
],
[
'ATM_ID' => 'AFF-MIL-TWR 2',
'FAC_IDENT' => 'AFF',
'LG_NAME' => 'BLACH BLAH ACADEMY',
'BASIC_TP' => 'MIL-TWR',
],
];
foreach ($decodedJson as $array) {
foreach ($array as $item) {
print $item; # => AFF-MIL-TWR 1
}
}

CSV to Associative Array (One column as key and another as value)

I need to convert a CSV file into an associative array, using one column as key and another as value. For example, I have this:
Application,Warehouse,Item,UPC,MFUSA Item No.,"PRODUCT DESCR1","PRODUCT DESCR2",Warehouse ID,Qty
INVENTORY:,Muscle Foods USA,1st STEP B12 LIQUID 16oz,673131100064,8890004,1st STEP B12 LIQUID 16oz,CHERRY CHARGE,11,29
INVENTORY:,Muscle Foods USA,1st STEP B12 LIQUID 16oz,673131100316,8890007,1st STEP B12 LIQUID 16oz,TROPICAL BLAST,11,26
INVENTORY:,Muscle Foods USA,1st STEP B12 LIQUID 16oz,673131100064,8890004,1st STEP B12 LIQUID 16oz,CHERRY CHARGE,12,6
I have to use the column UPC as the key and Qty as the value, so that the array looks like..
array(
'673131100064' => '29',
'673131100316 => '26',
'673131100064' => '6',
);
I have tried several solutions found in Google as well as here, but none of them are close to what I need to achieve. This Question was something similar, but it was written in Python.
Sorry for my poor knowledge in PHP. Can you please guide me to the right direction?
With array_map you can parse the csv data and have an array to do as you wish.
Example:
// Parsing the data in csv file
$csv = array_map('str_getcsv', file('path/file.csv'));
/*At this point you already have an array with the data but
* the first row is the header row in your csv file */
//remove header row
array_shift($csv);
$data = [];
//Walk the array and add the needed data into some another array
array_walk($csv, function($row) use (&$data) {
$data[$row[3]] = $row[8];
});
And that's it.
However the data you show as an example has duplicate UPCs. You will overwrite some data if you want an array with the structure 'UPC' => 'Qty' . You can't have duplicate keys in an array.
If what you are looking for is to get the total Qty for each UPCs then you just need to add the already existing Qty with the new one if the UPC key already exists.
// Parsing the data in csv file
$csv = array_map('str_getcsv', file('file.csv'));
//remove header row
array_shift($csv);
$data = [];
//Walk the array and add the needed data into another array
array_walk($csv, function($row) use (&$data) {
$data[$row[3]] = ($data[$row[3]] ? $data[$row[3]] + (int) $row[8] : (int) $row[8]);
});
Or longer but clearer.
//Walk the array and add the needed data into another array
array_walk($csv, function($row) use (&$data) {
if(!empty($data[$row[3]]))
{
$data[$row[3]] += (int) $row[8];
}
else {
$data[$row[3]] = (int) $row[8];
}
});
Explanation in the comments of the code below
$array = [];
// Open file "$file" and checking that it is not empty
if (($handle = fopen($file, "r")) !== false) {
// loop on each csv line, stopping at end of file
while (($data = fgetcsv($handle)) !== false) {
// Excluding header row & checking data is not empty
if ($data[0] !== 'Application' && !empty($data[0])) {
// fgetcsv returns an array, on your example UPC is on key 3 and Qty on key 9
$array[] = [$data[3] => $data[9]];
}
}
fclose($handle);
}
return $array;
Here the keys are hard-coded but maybe you have a way to put it dynamically, it depends of your code & workflow. This is just a simple (I hope) demonstration.
I use the SplfileObject for reading. Then the first line is used as the key for all values. array_column with the column names can now be used for the desired result.
$csv = new SplFileObject('datei.csv');
$csv->setFlags(SplFileObject::READ_CSV
| SplFileObject::SKIP_EMPTY
| SplFileObject::READ_AHEAD
| SplFileObject::DROP_NEW_LINE
);
//Combine first row as key with values
$csvArr = [];
foreach($csv as $key => $row){
if($key === 0) $firstRow = $row;
else $csvArr[] = array_combine($firstRow,$row);
}
$arrQty = array_column($csvArr,'Qty','UPC');

A 'for each' PHP loop within an existing Array[]

I'm trying to loop an array from a database into an existing array. The two codes work well alone but I only get an error when trying to combine them.... for example...
The current array (which is a list of spammer databases) look as such...
$dnsbl_lookup=array(
"access.redhawk.org",
"all.s5h.net",
"blacklist.woody.ch",
);
While the array I am trying to add is as so...
$values = $myOptions['re_i_'];
foreach ($values as $value) {
echo '"'.$value['database'].'",';
}
And I end up with the following...
$dnsbl_lookup=array(
"access.redhawk.org",
"all.s5h.net",
"blacklist.woody.ch",
$values = $myOptions['re_i_'];
foreach ($values as $value) {
echo '"'.$value['database'].'",';
}
);
Which, of course, only returns an error. Does anyone know how to do this properly or if it is even possible?
It looks like you want to merge the $dnsbl_lookup values with the database column values in $myOptions, which you can do with array_merge and array_column:
$dnsbl_lookup = array(
"access.redhawk.org",
"all.s5h.net",
"blacklist.woody.ch"
);
$dnsbl_lookup = array_merge($dnsbl_lookup, array_column($myOptions['re_i_'], 'database'));
Demo on 3v4l.org

php arrays: search for matching values in a table and replace with array keys

Please i want to loop through my table and compare values with an array in a php included file. If there is a match, return the array key of the matched item and replace it with the value of the table. I need help in returning the array keys from the include file and comparing it with the table values.
$myarray = array(
"12aaa"=>"hammer",
"22bbb"=>"pinchbar",
"33ccr"=>"wood" );
in my loop in a seperate file
include 'myarray.inc.php';
while($row = $db->fetchAssoc()){
foreach($row as $key => $val)
if $val has a match in myarray.inc.php
{
$val = str_replace($val,my_array_key);
}
}
So in essence, if my db table has hammer and wood, $val will produce 12aaa and 3ccr in the loop. Any help? Thanks a lot
You are looking for array_search which will return the key associated with a given value, if it exists.
$result = array_search( $val, $myarray );
if ($result !== false) {
$val = $result;
}
your array should look like
$myarray = array(
"hammer"=>"11aaa",
"pinchbar"=>"22bbb",
"wood"=>"33ccr" );
and code
if (isset($myarray[$key])){
//do stuff
}
I think you need the function in_array($val, $myarray);
If you don't want or can't change $myarray structure like #genesis proposed, you can make use of array_flip
include 'myarray.inc.php';
$myarray = array_flip($myarray);
while($row = $db->fetchAssoc()) {
foreach($row as $key => $val) {
if (isset($myarray[$val])) {
// Maybe you should use other variable instead of $val to avoid confusion
$val = $myarray[$val];
// Rest of your code
}
}
}

Adding an item to an associative array

//go through each question
foreach($file_data as $value) {
//separate the string by pipes and place in variables
list($category, $question) = explode('|', $value);
//place in assoc array
$data = array($category => $question);
print_r($data);
}
This is not working as it replaces the value of data. How can I have it add an associative value each loop though? $file_data is an array of data that has a dynamic size.
You can simply do this
$data += array($category => $question);
If your're running on php 5.4+
$data += [$category => $question];
I think you want $data[$category] = $question;
Or in case you want an array that maps categories to array of questions:
$data = array();
foreach($file_data as $value) {
list($category, $question) = explode('|', $value, 2);
if(!isset($data[$category])) {
$data[$category] = array();
}
$data[$category][] = $question;
}
print_r($data);
Before for loop:
$data = array();
Then in your loop:
$data[] = array($catagory => $question);
I know this is an old question but you can use:
array_push($data, array($category => $question));
This will push the array onto the end of your current array. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:
array_push($data,$question);
For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this
$data[$category]["test"] = $question
you can then call it (to test out the result by:
echo $data[$category]["test"];
which should print $question

Categories