目前我使用以下代码
<?php
// simulates result of db query for categories
$categories = array();
$categories[] = array('id' => 1, 'parent_id' => 0, 'name' => 'root');
$categories[] = array('id' => 2, 'parent_id' => 1, 'name' => 'Compact Discs');
$categories[] = array('id' => 3, 'parent_id' => 1, 'name' => 'Concert Souvenirs');
// simulates result of db query for products
$products = array();
$products[] = array('id' => 1, 'category_id' => 2, 'sku' => 'CD001', 'price'=>15.00, 'name' => 'CD: Greatest Hits');
$products[] = array('id' => 2, 'category_id' => 2, 'sku' => 'CD002', 'price'=>15.00, 'name' => 'CD: Unplugged');
$products[] = array('id' => 3, 'category_id' => 2, 'sku' => 'CD003', 'price'=>15.00, 'name' => 'CD: World Tour');
$products[] = array('id' => 4, 'category_id' => 3, 'sku' => 'PD001', 'price'=>10.00, 'name' => 'Souvenir Pin');
$products[] = array('id' => 5, 'category_id' => 3, 'sku' => 'PD002', 'price'=>10.00, 'name' => 'Mug');
$products[] = array('id' => 6, 'category_id' => 3, 'sku' => 'PD003', 'price'=>20.00, 'name' => 'Hat');
$products[] = array('id' => 7, 'category_id' => 3, 'sku' => 'PD004', 'price'=>12.00, 'name' => 'Summer Tour Poster');
$products[] = array('id' => 8, 'category_id' => 3, 'sku' => 'PD005', 'price'=>5.00, 'name' => 'Concert Program');
// create the response
$response = array('categories' => $categories, 'products' => $products);
// display the json encoded response
echo json_encode($response);
输出json结果就像这样
{"categories":[{"id":1,"parent_id":0,"name":"root"},{"id":2,"parent_id":1,"name":"Compact Discs"},{"id":3,"parent_id":1,"name":"Concert Souvenirs"}],"products":[{"id":1,"category_id":2,"sku":"CD001","price":15,"name":"CD: Greatest Hits"},{"id":2,"category_id":2,"sku":"CD002","price":15,"name":"CD: Unplugged"},{"id":3,"category_id":2,"sku":"CD003","price":15,"name":"CD: World Tour"},{"id":4,"category_id":3,"sku":"PD001","price":10,"name":"Souvenir Pin"},{"id":5,"category_id":3,"sku":"PD002","price":10,"name":"Mug"},{"id":6,"category_id":3,"sku":"PD003","price":20,"name":"Hat"},{"id":7,"category_id":3,"sku":"PD004","price":12,"name":"Summer Tour Poster"},{"id":8,"category_id":3,"sku":"PD005","price":5,"name":"Concert Program"}]}
但是,我希望使用Mysql从PHP获得相同的Json输出。我的数据库结构就像,
我应该如何编写我的PHP代码,以便从Mysql获取数据并获取上面的json结果?在此先感谢。
答案 0 :(得分:0)
我想最明确的方法是将你的sql结果集“转换”为你已经使用的相同结构 - 数组。这样您就不必更改任何其他内容 - 算法的其余部分将按原样运行。 因此,只需将结果行提取到与模拟时相同的结构数组。
答案 1 :(得分:0)
你接近它的方式对我来说似乎很好
示例摘录
$result = Array( 'Categories' => Array(), 'Products' => Array());
$stmt = $mysqli->prepare( 'SELECT id, parent_id, name FROM category' );
$stmt->bind_result( $id, $parent_id, $name );
$stmt->execute();
while( $stmt->fetch() ) {
$result['Categories'][] = Array( 'id' => $id, 'parent_id' => $parent_id, 'name' => $name );
}
$stmt->close();
//Do the same for the other one
$jsonstring = json_encode( $result );
从那里你应该能够自己弄清楚