Our Story: (short version below if you're eager to troubleshoot)
This question is asked after extensively searching for a way to get a multidimensional array (with named keys) back into it's CSV file. You might say: "But this is covered on multiple pages on SO, search better!" but we did, and the results we found we have tried to bend to our will, but failed.
The reason for this in the first place was to remove columns from the CSV that were interfering with the rest of our Query's and Code.
So now we're back to ask on SO:
We've read the CSV into a multidimensional Array, using the headers' 1st line as key names.
We then used unset($array[$i]['insert_date']); to remove the columns from the array
We also str_replace'd those columns names from our $header variable.
So we're extensively reading out csv's, putting them in awesome Arrays that have a numerical first index, and second dimension keys named after the first line of our CSV file.
We also have the original Header from CSV file stored in a variable handsomely called $header with a string like: '"brand";"category";"category_path"
So.. $header is a string, $array is our multidimensional array.
All we want to do, and we're stuck editing loop after loop, is to create a brand new File, that has our $header as the first line, and our $array's values as strings..
file to write to: $putfile = fopen("feeds/broken/lu-zz.csv", "rw");
we're using: fputcsv($file, $array,';','"'); to write
and preferably: \n line endings
In short:
from this:
array (size=3886)
0 =>
array (size=19)
'brand' => string 'Tommy Hilfiger' (length=14)
'category' => string '' (length=0)
'category_path' => string 'Heren|Jeans|Blue jeans' (length=22)
1 =>
array (size=19)
'brand' => string 'Marc Aurel' (length=10)
'category' => string '' (length=0)
'category_path' => string 'Dames|Jurken|Zomerjurken' (length=24)
2 =>
array (size=19)
'brand' => string 'Rinascimento' (length=12)
'category' => string '' (length=0)
'category_path' => string 'Dames|Jurken|Print jurken' (length=25)
To This
"brand";"category";"category_path"
"Tommy Hilfiger";"";"Heren|Jeans|Blue jeans" (/n)
"Marc Aurel";"";"Dames|Jurken|Zomerjurken" (/n)
"Rinascimento";"";"Dames|Jurken|Print jurken" (/n)
Last piece of code we tried:
{
foreach($subarray as $value){
for ($i=0, $m=count($value); $i<$m; $i++){
//$test = implode('";"',$subarray) ;
//$tmp = array();
$result = call_user_func_array('array_merge', $subarray);
//$tmp[]= array_merge($subsub[$i]);
var_dump($result);
fputcsv($putfile, $subarray,';','"');
}
}
} fclose($putfile);
This just returns the same value over and over again into an array:
foreach ($array as $subarray) {
foreach($subarray as $value){
for ($i=0, $m=count($value); $i<$m; $i++){
//$test = implode('";"',$subarray) ;
//$tmp = array();
print_r($subarray);
fputcsv($putfile, $subarray,';','"');
}
}
} fclose($putfile);
Solution in our case: Thanks to "Don't Panic" & "CBroe".
$putfile = fopen("feeds/stukkefeeds/lu-zz.csv", "wb");
$header = str_replace('"','',$header1);
$titel = explode(';',$header);
var_dump($titel);
// then write in your data
fputcsv($putfile, $titel,';','"');
foreach ($array as $line) {
fputcsv($putfile, $line,';','"');
}
It looks like you may be making it more complicated than it needs to be. If you have an $array that is the one you've shown that looks like:
array (size=3886)
0 =>
array (size=19)
'brand' => string 'Tommy Hilfiger' (length=14)
'category' => string '' (length=0)
'category_path' => string 'Heren|Jeans|Blue jeans' (length=22)
...
And you have a working file handle that you've opened with
$putfile = fopen("feeds/broken/lu-zz.csv", "w");
You shouldn't need a nested loop at all. You can get the header line by using array_keys on the first item in the array (or any item, really), write it to the file with fputcsv, and then loop over the array and write each line of data, also with fputcsv.
$first_line = reset($array); // get the first line
fputcsv($putfile, array_keys($first_line)); // use its keys to write the headers
// then write in your data
foreach ($array as $line) {
fputcsv($putfile, $line,';','"');
}
Looks like you are thinking way too complicated here ...
$firstIteration = true;
foreach($yourArray as $elem) {
if($firstIteration ) { // if this is the first array element,
// write out its keys to create the CSV heading line
echo implode(';', array_keys($elem)) .'<br>';
$firstIteration = false;
}
echo implode(';', $elem) .'<br>'; // output the data for each array element
}
(Notice that I used echo and implode here for demonstration purposes; the result will not have the enclosing " - switching that out for writing CSV to the file again should be no issue.)
Related
I am inserting string with multiple delimiters and split it using explode function to mysql database table but i failed in building proper logic.
I tried with single delimiter i-e , and successfully insert that record.
Now i want to split string with | and ,.
I used for row separation and | for value seperation.
i-e
$var = "Facebook|http://facebook.com/123|12312|12 to 13,Twitter|http://twitter.com/231|12321|12 to 13";
$cat="2,3";
$i=0;
$arrayOfCategories = explode(",", $cat);
foreach ($arrayOfCategories as $categories) {
$datas[$i]['UserID'] = 2;
$datas[$i]['CatID'] = $categories;
$i++;
}
var_dump($datas);
Format showed using var_dump is the format which i want to insert using insert_batch of codeigniter.
This is the expected output
array (size=2)
0 => array (size=2)
'SocialName' => string 'Facebook'
'URL' => string 'facebook.com/123'
1 => array (size=2)
'SocialName' => string 'Twitter'
'URL' => string 'twitter.com/231'
$array = array();
$string = "Facebook|http://facebook.com/123|12312|12 to 13,Twitter|http://twitter.com/231|12321|12 to 13";
$rows = explode(',', $string);
foreach ($rows as $row) {
$values = explode('|', $row);
$array[] = array('SocialName' => $values[0], 'URL' => $values[1]);
}
var_dump($array);
Create an array $array to store the final result in.
Now, split the input string $string on , using explode, this gives you the "rows".
Go through all the rows (foreach), and split each row on the | (explode), this gives you the "values".
The first value $values[0] is the "SocialName", and the second value $values[1] is the "URL", so add those to a new array, and add that new array to the final result array $array.
So here's my code:
foreach ($result->devices as $device) {
$flag = false;
foreach ($device as $key => $value) {
if(!$flag){
var_dump($key);
$flag = true;
}
var_dump($value);
}
}
What I try to achieve is to only print the key (description, brand, etc...) only once but print the value of all those keys for every device found. This is to make it eventually save as an .csv
Note: $result = a multidimensional array where I'm only interested in the devices section of it, hence the $result->devices.
The way this works now is it only prints the first key for every device found, what I get now looks something like:
string 'deviceId' (length=8) // keeps getting repeated
int 4268
string 'beschrijving nr 53' (length=18)
...
string 'deviceId' (length=8) // keeps getting repeated
int 4267
string 'Weer een tooltje' (length=16)
What I try to get is something resembling:
string 'deviceId' (length=8)
string 'description' (length=??)
string 'status' (length=??)
... // rest of keys, followed by devices
int 4268
string 'beschrijving nr 53' (length=18)
... // rest of values, followed by other devices
int 4267
string 'Weer een tooltje' (length=16)
I'm sure it's something simple like the wrong order of operation or moving something in/out a certain loop, but after having tried various variations, I'm none the wiser.
So to whom may solve this mystery, I thank you greatly.
So, I suppose, your data looks kind of like this?
$result = (object)[];
$result->devices = [
['deviceId' => 1, 'description' => 'desc1', 'status' => 'status14'],
['deviceId' => 2, 'description' => 'desc2', 'status' => 'status15'],
['deviceId' => 3, 'description' => 'desc3', 'status' => 'status16'],
['deviceId' => 4, 'description' => 'desc2', 'status' => 'status17'],
];
Then to create a CSV file from it I would go like this:
$fp = fopen('csv.csv', 'w+');
foreach($result->devices as $i => $device)
{
// First row? Write headers (keys) first!
if($i == 0) fputcsv($fp, array_keys($device));
// Write data rows
fputcsv($fp, array_values($device));
}
fclose($fp);
This way, you will get this:
deviceID,description,status
1,desc1,status14
2,desc2,status15
3,desc3,status16
4,desc4,status17
Is this what you need?
Thanks to Oleg Dubas, I've found the problem. It appears I was overcomplicating things (as I tend to do), in combination with trying to print out parts of an object, instead of having the object cast into an array. That's why when I tried a similar approach like this before, it didn't work. This is the new and working code:
foreach ($result->devices as $key => $device) {
if ($key == 0) {
fputcsv($out, array_keys((array)$device), "\t");
}
fputcsv($out, array_values((array)$device), "\t");
}
As you can see it is almost identical to Oleg's code, but I just had to cast the object to an associative array.
Thanks again for the help, Oleg. It was much appreciated.
I have a string:
01;Tommy;32;Coder&&02;Annie;20;Seller
I want it like this:
array (size=2)
0 =>
array (size=4)
0 => string '01' (length=2)
1 => string 'Tommy' (length=5)
2 => int 42
3 => string 'Coder' (length=5)
1 =>
array (size=4)
0 => string '02' (length=2)
1 => string 'Annie' (length=5)
2 => int 20
3 => string 'Seller' (length=6)
Hope you can help me, thank you!
Not sure if the datatypes will be matching (as I believe it's all in a string) but here's the code
$myarray = array();
foreach(explode("&&",$mystring) as $key=>$val)
{
$myarray[] = explode(";",$val);
}
The explode command takes a string and turns it into an array based on a certain 'split key' which is && in your case
but since this is a dual array, I had to pass it through a foreach and another explode to solve.
It's very simple. First you need to explode the string by && and then traverse through array exploded by &&. And explode each element of an array by ;.
Like this,
<?php
$str="01;Tommy;32;Coder&&02;Annie;20;Seller";
$array=explode("&&",$str);
foreach($array as $key=>$val){
$array[$key]=explode(";",$val);
}
print_r($array);
Demo: https://eval.in/629507
you should just have to split on '&&', then split the results by ';' to create your new two dimensional array:
// $string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
// declare output
$output = [];
// create array of item strings
$itemarray = explode('&&',$string);
// loop through item strings
foreach($itemarray as $itemstring) {
// create array of item values
$subarray = explode(';',$itemstring);
// cast age to int
$subarray[2] = (int) $subarray[2]; // only useful for validation
// push subarray onto output array
$output[] = $subarray;
}
// $output = [['01','Tommy',32,'Coder'],['02','Annie',20,'Seller']];
keep in mind that since php variables are not typed, casting of strings to ints or keeping ints as strings will only last depending on how the values are used, however variable type casting can help validate data and keep the wrong kind of values out of your objects.
good luck!
There is another appropach of solving this problem. Here I used array_map() with anonymous function:
$string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
$result = array_map(function($value){return explode(';',$value);}, explode('&&', $string));
I am trying to produce a HTML list grouped by "groupName" from the array below.
array (size=30)
0 =>
array (size=4)
'groupOrder' => string '1' (length=1)
'groupName' => string 'Class' (length=11)
'txt' => string '............' (length=32)
'ID' => string '6' (length=1)
1 =>
array (size=4)
'groupOrder' => string '1' (length=1)
'groupName' => string 'Size' (length=11)
'txt' => string '..................' (length=34)
'ID' => string '6' (length=1)
2 =>
...
So I'd like produce something like this pseudo list:
groupName
txt
txt
txt
next GroupName
txt
txt
...
So my code looks like this
foreach ($datafeed as $val => $row) {
if (($datafeed[$val]['groupName']) == next($datafeed[$val]['groupName'])) {
//same group - do nothing
} else {
echo $datafeed[$val]['groupName'];
}
echo "<li>".$row['txt']. "</li>";
}
But I'm getting errors about "next() expects parameter 1 to be array, string given".
I've tried all sorts of different syntax, but I'm not making much progress. How do I compare two values in a nested array?
You misinterpreted the meaning of the function next(): you cannot query it for an array element. It manipulates the internal array pointer tied with the array itself, not with some its element. From the PHP documentation:
Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.
and see also a description of next.
Since the foreach loop crucially depends on the value of the array pointer, messing with the array pointer will ruin the loop: you probably see every second element in the loop, because at every iteration once next() is called by your foreach loop and then once by yourself.
The simplest thing for you is probably to use the old good for loop:
for ($i = 0; $i < length ($array); $i++)
{
if ($i == 0 || $array[$i] != $array[$i - 1])
echo "New group!\n";
echo $array[$i];
}
This doesn't answer your question directly, but you'd be better off restructuring your array so that they're grouped, and you don't need to perform any logic within the loop to check the groupName. Currently, you're relying on the next groupName to match the current groupName, but if they're not sequential, they won't be grouped.
You could do something like this:
$output = array();
foreach ($datafeed as $feed) {
$output[$feed['groupName']][] = $feed;
}
Here's a demo
You should not use next inside a foreach loop anyway, since you'll get conflicting array pointer movements. Simply store the last value:
$last = null;
foreach (...) {
if ($last != $row['current']) {
// new group
}
$last = $row['current'];
...
}
I am trying to figure out how to get values out of a checkbox array. The checkbox array var_dump looks like the following:
array (size=50)
0 => string '104702|0' (length=8)
1 => string '52278|1' (length=7)
2 => string '69891|1' (length=7)
3 => string '153335|1' (length=8)
4 => string '131140|1' (length=8)
. . .
I am sending two different IDs in each array value, separated by a pipe and would like to assign each part to different variables, $variable1, $variable2, so I can use them in a database query. How can I do this?
Thanks for your help.
EDIT: Even though I've accepted an answer below, here is the complete answer I was looking for:
To get the values out of the above array so I can use them in my database query, I did the following to first break them apart:
foreach ($input as $key => $value) {
$this->combinedIds[] = explode('|', $value);
}
Then, to get the values into separate variables, I did the following:
foreach ($this->combinedIds as $key => $value) {
$firstId = $value[0];
$secondId = $value[1]
// do something with the values ...
}
Use foreach loop on the array and explode each value with pipe symbol. Something like this :
foreach ($arr as $val)
{
$newData = explode("|", $val);
}
A different variant (using an anonymous function) would be something like:
$values = array_map(function ($input) { $tmp = explode("|", $input); return ["id1" => current($tmp), "id2" => end($tmp)]; }, $array);.
This is written for PHP 5.4+. If you need a version compatible with PHP 5.3 and downwards, just substitute the brackets with its corresponding array(...) equivalent.