Php code
<?php
$d1 = "a:1,b:2,c:3,d:4"; //field number variable.. sometimes 4 or 10
$d2 = explode(',', $d1);
foreach ($d2 as $key => $value) {
$arr1 = explode(':',$d2[$key]);
foreach ($arr1 as $key1 => $value1) {
$arr1[] = $key1;
}
echo $arr1[0] . "," . $arr1[1] . ",";
}
?>
Result
a,1,b,2,c,3,d,4,
Fields (a,b,c,d) (field number variable.. sometimes 4 or 10..)
Values (1,2,3,4)
Expected result
Insert into Table1 (a,b,c,d) values (1,2,3,4)
How can i do to make this result ? (it would be good if it is a complete example)
Thanks for all answers
I know preg_split() will do the task fine. But last day when I got the similar problem I did this solution with the help of http://php.net/manual/en/function.explode.php#111307
function multiexplode ($delimiters,$string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
$d1 = "a:1,b:2,c:3,d:4";
$result = implode(',',multiexplode(array(",",".","|",":"),$d1));
echo $result;
See demo : https://eval.in/871705
Edit: As per comment by SO
$d1 = "a:1,b:2,c:3,d:4"; //field number variable.. sometimes 4 or 10
$d2 = explode(',', $d1);
$result = [];
foreach ($d2 as $key => $value) {
list($k,$v) = explode(':',$value);
$result[$k] = $v;
}
print '<pre>';
print_r($result);
print '</pre>';
echo "INSERT INTO table1 (".implode(', ',array_keys($result)). ") VALUES (".implode(', ',array_values($result)). ")";
In recent PHP versions you can destructure the result of explode() on $d2[$key] (you should improve your naming, it helps!) into two separate arrays like so:
$keys = $values = [];
foreach (explode(',', $d1) as $parameter)
[$keys[], $values[]] = explode(':', $parameter);
var_dump($keys, $values);
var_dump(array_combine($keys, $values));
After that you can simply build that into a query. However, it seems like your data might be user-provided so you should be very wary of that data. You seem to be almost introducing a SQL injection vulnerability in your code.
I suggest checking the $keys array against a whitelist and after that properly escaping all $values before using any of this in a query. You may find some info here: PDO with INSERT INTO through prepared statements
You can use preg_split.
$output = preg_split( "/ (,|:) /", $input );
Next, you can do a check in a loop.
foreach ($output as $value)
{
if(is_number($value))
$keys[] = $value;
else
$values[] = $value;
}
Since the string is close to json format i think making it a true json and decode it means no looping or exploding is an efficient solution.
$d1 = "a:1,b:2,c:3,d:4";
$d1 = "{\"".str_replace(array(",",":"),array('","','":"'), $d1)."\"}";
$arr = json_decode($d1, true);
$table = array_keys($arr);
$values = array_values($arr);
Var_dump($table);
Var_dump($values);
https://3v4l.org/Yqrbe
Edit; if you need the string you named as expected result use this:
$str ="Insert into Table1 (". Implode(",", $table) .") values (" . Implode(",", $values).")";
Echo $str;
Used below code.
Just little bit changes in your code this is working fine.
$d1 = "a:1,b:2,c:3,d:4"; //field number variable.. sometimes 4 or 10
$d2 = explode(',', $d1);
$colums = $values = array();
foreach ($d2 as $key => $value) {
$arr1 = explode(':',$value);
$colums[] = "`".$arr1[0]."`";
$values[] = "'".$arr1[1]."'";
}
$sql = 'insert into `Table1` ('.implode(",",$colums).') values ('.implode(",",$values).')';
Try with following logic:
foreach ($d2 as $key => $value) {
$arr1 = explode(':', $value);
if (count($arr1) == 2){
$arr[$arr1[0]] = $arr1[1];
}
}
Get all fields and values as comma separated:
$fields = array_keys($arr);
¢values = array_values($arr);
And use these variables into your query:
$fields = implode(",", array_keys($arr));
$values = implode(",", array_values($arr));
$query = "INSERT INTO Table1 (".$fields.") VALUES (".$values.")";
Running snipet: https://ideone.com/EXAPOt
Related
I am trying to merge two strings in a specific way.
Essentially I need to merge the first two strings into a third with a pipe symbol between them then separated by commas:
$merge1 = "id1,id2,id3"
$merge2 = "data1,data2,data3"
Those two would become:
$merged = "id1|data1,id2|data2,id3|data3"
I hope this makes sense?
I mean there is no PHP function that can output what you need.
Code produced desired output could be
<?php
$merge1 = "id1,id2,id3";
$merge2 = "data1,data2,data3";
$merged = [];
$arr1 = explode(',', $merge1);
$arr2 = explode(',', $merge2);
foreach ($arr1 as $key => $val) {
$merged[] = $val . '|' . $arr2[$key];
}
echo implode(',', $merged);
// id1|data1,id2|data2,id3|data3
This script will help you
<?php
$merge1 = "id1,id2,id3";
$merge2 = "data1,data2,data3";
$merge1 = explode(",", $merge1);
$merge2 = explode(",", $merge2);
$final = [];
foreach ($merge1 as $index => $value) {
$final[] = $value . "|" . $merge2[$index];
}
$final = implode(",", $final);
print_r($final);
output
id1|data1,id2|data2,id3|data3
Try this.
<?php
$merge1 = "id1,id2,id3";
$merge2 = "data1,data2,data3";
$merge1 = explode(",",$merge1);
$merge2 = explode(",",$merge2);
$mergeArr = array_combine($merge1,$merge2);
$mergeStr = [];
foreach($mergeArr as $k => $v) {
$mergeStr[] = $k.'|'.$v;
}
$mergeStr = implode(",",$mergeStr);
echo $mergeStr;
?>
This is my code:
$arr = array();
$dns_1 = mysqli_query($conn, $query);
$dns_2 = mysqli_query($conn, $query);
$d1 = mysqli_fetch_assoc($dns_1);
$d2 = mysqli_fetch_assoc($dns_2);
$arr[1] = $d1;
$arr[2] = $d2;
foreach($arr as $key => $values) {
echo $key."".$values;
}
Output:
Notice: Array to string conversion in C:\xampp\htdocs\index.php on line 79
1Array
Why can't I echo the $values in my foreach??
I don't want to use implode if possible
Thank you!
Because $values is an array, you can't echo it as a string. If you don't want to use implode(), you can use print_r() like this:
foreach($arr as $key => $values) {
echo $key . ':';
print_r($value);
}
I have function that is supposed to match arrays together using the array_intersect function. I'm trying to match a product name with possible offers with same name from multiple merchants. My issue now is I'm using nested foreach loops and whenever I run it, the loop is always infinite and it prints duplicate results.
Here's the function:
function get_matching_product3(&$catalogue, $stock) {
$stockSmallCase = array_map('strtolower', $stock);
$catalogueSmallCase = array_map('strtolower', $catalogue);
foreach ($catalogueSmallCase as $key => $value)
{
$catalogueKey = $key;
$catalogueValue = $value;
$catalogueTokens = explode (' ', $catalogueValue);
foreach ($stockSmallCase as $key => $value) {
$stockKey = $key;
$stockValue = $value;
$stockTokens = explode (' ', $stockValue);
$match= array_intersect($stockTokens, $catalogueTokens);
$m = count($match);
$t = count($catalogueTokens);
//echo $m;
//echo $t;
if (($m > 1) && (($m / $t) * 100) >= 90) {
//print_r($match);
echo = $catalogueKey." ".$stockKey;
//echo "</br>";
//echo $stockKey;
}
}
}
return null;
}
You have
foreach ($catalogueSmallCase as $key => $value)
and
foreach ($stockSmallCase as $key => $value)
I think the problem came from the $key and $value variables. They are probably misunderstood by php at some time of the loop.
Try changing it in order to différenciates it.
I'm having trouble using preg_match_all to split a string into key value pairs. An example of my string:
"%Title:Movie%Sortable%Writer:%Indexed:false%"
Where I expect results like:
$result['Title'] = 'Movie';
$result['Sortable'] = '';
$result['Writer'] = '';
$result['Indexed'] = 'false';
I can split the string using preg_match('/%/',$str,-1,PREG_SPLIT_NO_EMPTY); but it returns an indexed array. I need an associative array so that order is not important and I can use the key in a switch statement. What would be the correct regex to use in preg_match_all?
Try with:
$input = "%Title:Movie%Sortable%Writer:%Indexed:false%";
$output = array();
$data = explode('%', $input);
foreach ($data as $item) {
list($key, $value) = explode(':', $item);
$output[$key] = $value;
}
<?php
$arr = array();
$string = "%Title:Movie%Sortable%Writer:%Indexed:false%";
$d = explode('%', $string);
foreach($d as $item){
list($key,$value) = explode(':', $item);
$arr[$key] = $value;
}
print_r($arr);
?>
My data variable:
1=icon_arrow.gif,2=icon_arrow.gif,3=icon_arrow.gif
I need it to be grouped by the value after =, so in this case it should look like this:
$out = array('icon_arrow.gif' => '1, 2, 3');
The 'icon_arrow.gif' field need to be unique, and can't repeat.
How it can be done?
Initialize an array:
$array = array();
Explode the input by ,, store results as an array based on a sub-explode of it by =:
foreach(explode(',', $string) as $p)
{
list($i, $n) = explode('=',$p);
$array[$n][] = $i;
}
Implode then the result with ,:
foreach($array as &$v)
$v = implode(', ', $v);
unset($v);
Done.
Just for fun. With no special chars this should also work.
$str="1=icon_arrow.gif,2=icon_arrow.gif,3=icon_arrow.gif,4=x.gif";
$str = str_replace(',', '&', $str);
parse_str($str, $array);
$result = array();
foreach($array as $k=>$v)
$result[$v] = (isset($result[$v]) ? $result[$v] . ", " : "") . $k;