Robin Vlaar Robin Vlaar - 3 years ago 187
PHP Question

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

Answer Source

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)). ")";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download