Robin Vlaar
Robin Vlaar

Reputation: 27

php multiple array multiple explode

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

Upvotes: 0

Views: 3769

Answers (6)

Ankur Garg
Ankur Garg

Reputation: 605

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

Upvotes: 0

sheraz
sheraz

Reputation: 464

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

Upvotes: 0

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

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

Upvotes: 1

Andreas
Andreas

Reputation: 23958

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;

Upvotes: 0

NSSec
NSSec

Reputation: 4551

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

Upvotes: 2

Stranger
Stranger

Reputation: 134

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;    

   }

Upvotes: 0

Related Questions