簡單preg_match
與foreach
能做到這一點:
<?php
$link = mysqli_connect('host', 'user', 'pass', 'db') or die(mysqli_error($link));
$query = "SELECT * FROM sql_table ORDER BY id";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$json = array();
$rc = 0;
while($row = mysqli_fetch_assoc($result)){
foreach($row as $rowName => $rowValue){
if(preg_match_all('/\d+/', $rowName) !== 0){
$index = substr($rowName, 0,1);
$json[$rc]['data'][$index][$rowName] = $rowValue;
}else{
$json[$rc]['data'][$rowName] = $rowValue;
}
}
$rc++;
}
print_r(json_encode($json));
?>
輸出:
[{
"data": {
"id": "1",
"a": "x",
"b": "y",
"c": {
"c1": "z1",
"c2": "z2",
"c3": "z3"
},
"d": "w"
}
}, {
"data": {
"id": "2",
"a": "xx",
"b": "yy",
"c": {
"c1": "zz1",
"c2": "zz2",
"c3": "zz3"
},
"d": "ww"
}
}]
This w生病與任何類似於你的列(f4, f5, r, t
等)。
我已經嘗試了一些東西,但他們沒有接近預期的輸出。 – suku
如果你有多於一行的表格,那該怎麼辦? JSON應該是怎樣的? – mitkosoft
@mitkosoft:我添加了json應該查找多行的方法 – suku