如何将 OPTIONS 列拆分为数组,其中数组的索引将为字符串中的数字。例如,使用此
[OPTIONS] => {0: 'phy','chem','bio'},{1: 'webtech','algo'}
将导致
Array
(
[0] => [
[0] => 'phy',
[1] => 'chem',
[2] => 'bio'
],
[1] => [
[0] => 'webtech',
[1] => 'algo'
]
)
Index.php
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=mydb','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Eror");
}
$stmt = $pdo->query("SELECT * FROM table");
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($data as $key) {
echo "<pre>";
print_r($key);
echo "</pre>";
}
?>
结果
stdClass Object
(
[ID] => 1
[FACULTY_NAME] => APPLIED SCIENCE
[DEPT] => SLT,COMPUTER SCIENCE,FOOD TECHNOLOGY,NUD,HMT,
[OPTIONS] => {0: 'phy','chem','bio'},{1: 'webtech','algo'}
)
答案 0 :(得分:3)
不同爆炸和str_replace的组合将为您提供结果。
我同时使用爆炸和多重爆炸。
首先,我展开到不同的子数组,然后再进行多重分解,并且第一个值是键,其余的是值,然后用array_slice拆分。
$str = "{0: 'phy','chem','bio'},{1: 'webtech','algo'}";
$arr = explode("},{", str_replace("'", "", $str));
foreach($arr as $a){
$temp = multiexplode([": ", ","], str_replace(["{", "}"], "", $a));
$res[$temp[0]] = array_slice($temp, 1);
}
var_dump($res);
function multiexplode ($delimiters,$string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
$ res:
array(2) {
[0]=>
array(3) {
[0]=>
string(3) "phy"
[1]=>
string(4) "chem"
[2]=>
string(3) "bio"
}
[1]=>
array(2) {
[0]=>
string(7) "webtech"
[1]=>
string(4) "algo"
}
}