String with Multiple delimiters- MySQL Insert row by row - php

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.

Related

Explode string with two different separators to create multidimensional array

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));

From CSV to array with headerkeys, now back to CSV

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.)

Dynamic Array Overwriting

I'm new to array and I have a decrypt function and sql query. Process is I query in the database and return the $get in an array like so:
array (size=1)
0 =>
array (size=3)
'Username' => string 'joenefloresca' (length=13)
'MiddleName' => string 'Estero' (length=6)
'Email' => string 'joenefloresca#gmail.com' (length=23)
What I want is to use my decrpyt function (data is encrypted, above is just an example). When I decrypt
it I want it to overwrite $get array with the decrypted values. I can do it this way,
foreach( $get as $key => $result )
{
$get[$key]['Username'] = $decr->decrypt($result['Username']);
$get[$key]['MiddleName'] = $decr->decrypt($result['MiddleName']);
$get[$key]['Email'] = $decr->decrypt($result['Email']);
}
But I can do that if my Fields like Username,MiddleName,Email is fixed in the sql query, what if
it is dynamic? Fields in the query is defined by the user, ex. What if Username is the only field? or Username and Email only? How can I overwrite the array with the decrypted one with the selected Field only?
Thanks.
Just nest another loop inside if you do not want to explicitly set the index you want:
foreach($get as $key => $result) {
foreach($result as $k => $val) { // will loop for each piece/copy of `$result`
$get[$key][$k] = $decr->decrypt($val);
}
}

How to get next value in a multidimensional array

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'];
...
}

PHP Get Values Out of Checkbox Array

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.

Categories