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;
?>
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
I'm trying to loop some array using foreach. This is the code which demonstrates what I'm doing
$q = "SELECT * "
."FROM ".TBL_FRUITSDETAILS."";
$fruitsdetails = $database->query($q);
$var = array();
while($line = mysql_fetch_assoc($fruitsdetails)){
$var[] = $line;
}
$q = "SELECT * "
."FROM ".TBL_NUMDETAILS."";
$numdetails = $database->query($q);
$var2 = array();
while($line2 = mysql_fetch_assoc($numdetails)){
$var2[] = $line2;
// $n++;
}
$out = array();
foreach ($var as $key => $value){
// $out[] = array_merge_recursive($value, $var2[$key]);
foreach ($var2 as $key => $value) {
$out1[] = array_merge_recursive($var[$key], $var2[$key]);
}
}
print_r(json_encode($out1));
However, this outputs
appleone
bananatwo
appleone
bananatwo
and I want to display it like this instead
appleone
appletwo
bananaone
bananatwo
Try this,
$var = array (1,2);
$var2 = array (a,b);
$out = array();
foreach ($var as $key => $value){
foreach($var2 as $k=>$v){
$out[] = $value.$v;
}
}
print_r(json_encode($out));
I think your loop should be something like this. There's no need of using array_merge_recursive function
$var = array (1,2);
$var2 = array ('a','b');
$result = array();
foreach($var as $key => $val){
foreach($var2 as $k => $v){
$result[] = $val.$v;
}
}
There is no need to use array_merge_recursive just a nested loop will suffice:
$var = array (1,2);
$var2 = array ('a','b');
$out = array();
foreach($var as $arrayNumeric){
foreach($var2 as $arrayAlphaNumeric){
$out[] = $arrayNumeric.$arrayAlphaNumeric;
}
}
I want to store result of a query as associative array. Below is my code that generates the query result below.
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
foreach ($data_array as $key => $value)
{
echo $key.'=>'.$value.'<br />';
}
?>
This gives me output as
19=>Array
20=>Array
21=>Array
27=>Array
29=>Array
But I should get
19 -> [4,5],
20 -> [5],
21=>[4,6],
// and so on
$value is an array, you can't use echo on arrays
Don't loop just do a var_dump()
$data_array = array();
while($rs = mysql_fetch_assoc($result)){
$data_array[$rs['id']][]=$rs['Sprinkler_ID'];
}
var_dump($data_array);//or print_r($data_array);
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
$out = '';
$count = count($data_array);
$iter = 0;
foreach ($data_array as $key => $value)
{
$out.= $key.'=>[';
foreach ($value as $val) {
$out.=$val.',';
}
$out = rtrim($out, ",");
$out.= ']';
if ($iter < ($count-1)) {
$out.=',<br />';
}
$iter++;
}
echo $out;
You need an inner foreach loop to handle printing the array in $value as this is a multi dimensional array. The preceding is an example of how it could look to produce the exact output you requested. If you are looking for a dump of the values, then please use the var_dump solution provided by #meda.
There are two issues in your code. The first is that $value is an array, the second is that this array only contains one item.
Try this:
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key][] = $value;
}
foreach ($data_array as $key => $values)
{
echo $key.'=> [';
foreach($values as $value)
echo $value . ',';
echo ']<br />';
}
I have the following key/value from my $_POST variable:
Array
(
'translations_0_comment' => 'Greetings from UK'
)
What I would like is to set this values to the following array
$data[translations][0][comment] = 'Greetings from UK';
So the idea is that I can have anything in my KEY values, and from that I will populate an array.
Is there any safe way to do this without using eval() ?
All help is appreciated.
UPDATE:
this would be the idea with eval()
foreach ($_POST as $key => $dataValue) {
$a = explode("_", $key);
$builder = '$object';
foreach ($a as $value) {
$builder.='['.$value.']';
}
$builder.=' = '.$dataValue.';';
eval($builder);
}
I think you are looking for this
function set_value($object, $paths, $value, $index){
$key = $paths[$index];
$sub_object = $object[$key];
if (!is_array($sub_object)){
$object[$key] = $value;
}else{
$index = $index+1;
$object[$key] = set_value($sub_object, $paths, $value, $index);
}
return $object;
}
explode() is what you need:
$data = array();
foreach ($postData as $key => $val) {
$explodedKey = explode('_', $key);
$data[$explodedKey[0]][$explodedKey[1]][explodedKey[2]] = $val;
}
No need to use eval().
I think this is what you are looking for
Example
In your form which generate the $_POST data rename the input attribute as follows
<input name="data[translations][0][comment]" />
and now your $_POST['data'] will be an array
$data = array();
foreach ($_POST as $keys => $val) {
$keys_list = explode('_', $keys);
$link = &$data;
foreach ($keys_list as $key) {
$link[$key] = $val;
$link = &$link[$key];
}
}
Try this one sir.
$array = array
(
'TRY_THIS_ONE_SIR_PLEASE_THANKS' => 'Greetings from UK'
);
$array1 = array_keys($array);
$arrValue = array_values($array);
$array1 = explode("_", $array1[0]);
$ctr = count($array1);
for($i=0; $i<$ctr; $i++)
{
$start .= "array(\"".$array1[$i]."\" => ";
$end .=")";
}
$start = $start ."\"".$arrValue[0]."\"".$end;
eval("\$arr = $start;");
print_r($arr);