如何在php

时间:2017-12-28 04:15:29

标签: php arrays

我有两张表,即类别&存储即可。现在我需要使用php以数组格式从这些表中获取数据。我以数组格式从这些表中获取数据的位置。但我需要根据类别名称对这些数据进行分类。

以下是我用来检索数据的表格。 Tables

这是我从db获取数据的php代码。

<?php
$sql_query = "SELECT store_id, store_name, store_url, category_id, (SELECT categories_name FROM categories_list WHERE categories_id = stores_list.category_id) AS category_name FROM  `stores_list`  order by category_id asc";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$result=mysqli_query($conn, $sql_query); 
while($row=mysqli_fetch_array($result)){
 $data["countries_list"][] = array("category_name" => $row['category_name'],
        "stores_list"=>array("store_id" => $row['store_id'], "store_name" => $row['store_name'],"store_url" => $row['store_url']));
 }
echo json_encode($data);
?>

以下是我为上述代码获得的输出。 getting output

这是所需的输出。 desired output

1 个答案:

答案 0 :(得分:1)

你能试试吗?

$sql_query = "SELECT store_id, store_name, store_url, category_id, (SELECT categories_name FROM categories_list WHERE categories_id = stores_list.category_id) AS category_name FROM  `stores_list`  order by category_id asc";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result=mysqli_query($conn, $sql_query);
while($row=mysqli_fetch_array($result)){
    $data["countries_list"][$row['category_name']] = array("category_name" => $row['category_name']);
    $data["countries_list"][$row['category_name']]["stores_list"]["stores_info"][] = array("store_id" => $row['store_id'], "store_name" => $row['store_name'],"store_url" => $row['store_url']);
}
$data["countries_list"] = array_values($data["countries_list"]);
echo json_encode($data);